我希望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();
谁能告诉我手头的问题是什么以及如何解决?
答案 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"