2017-05-27 179 views
1

我想订购pincode字符串为空,当我试图将pincode转换为一个整数排序时,我收到一个错误。Linq OrderBy问题当转换字符串为int与空格

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(); 

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

回答

1

你可以先筛选出来避免空字符串。即

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

不过,如果你想保持Student对象有一个空字符串,而是与"0"取代他们Pincode属性,你可以试试这个:

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

我们需要pin码之间移除空间数字。例如:“600 001”删除600和001之间的空格。 我试过下面的代码,工作正常,谢谢回复:) objStudentList = objStudentList.OrderBy(a => string.IsNullOrEmpty(a.Pincode.Trim()) int.Parse(“0”): int.Parse(Regex.Replace(a.Pincode.Replace(“”,“”).Replace(“\ t”,“”),@“\ t | \ n | \ r“,”“)))。ToList(); – Gopi

0

的原因是,你想隐蔽一个空字符串为int。如果你想获得0结果,则必须更换"""0"