使用空格将字符串转换为int时出现Linq OrderBy问题

时间:2017-05-27 18:34:02

标签: c# linq

我希望pincode以字符串为空排序,当我尝试将pincode转换为整数进行排序时,我收到错误。

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Pincode { get; set; }
}

List<Student> objStudentList = new List<Student>();
objStudentList.Add(new Student() { Id = 1, Name = "gopi", City="Chennai", Pincode = "600002" });
objStudentList.Add(new Student() { Id = 2, Name = "ravi", City = "Bangulor", Pincode = "600 001" });
objStudentList.Add(new Student() { Id = 3, Name = "mani", City = "Madurai", Pincode = "600 007" });
objStudentList.Add(new Student() { Id = 4, Name = "anbu", City = "Thiruchi", Pincode = "600 005" });
objStudentList.Add(new Student() { Id = 4, Name = "kumar", City = "Thiruchi", Pincode = "" });


objStudentList = objStudentList.OrderBy(a => int.Parse(Regex.Replace(a.Pincode.Replace(" ", "").Replace("\t", ""), @"\t|\n|\r", ""))).ToList();

谁能告诉我手头的问题是什么以及如何解决?

2 个答案:

答案 0 :(得分:2)

首先将它们过滤掉,你可以避免空字符串。即。

objStudentList = objStudentList.Where(a => !string.IsNullOrEmpty(a.Pincode))
                               .OrderBy(a => int.Parse(a.Pincode)).ToList();

但是,如果您想保留Student个空字符串对象,而是将Pincode属性替换为"0",则可以尝试:

objStudentList = objStudentList.OrderBy(a => string.IsNullOrEmpty(a.Pincode) ? int.Parse("0") : int.Parse(a.Pincode))
                               .ToList();

答案 1 :(得分:0)

原因是你试图将空字符串转换为int。如果您希望获得0,则必须将""替换为"0"

相关问题