2017-05-27 51 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"