2013-03-17 164 views
0

如何使用c1元素對List<ABC>進行排序?非常感謝你!如何根據對象的屬性對列表進行排序

public class ABC 
{ 
    public string c0 { get; set; } 
    public string c1 { get; set; } 
    public string c2 { get; set; } 
} 
public partial class MainWindow : Window 
{ 
    public List<ABC> items = new List<ABC>(); 
    public MainWindow() 
    { 
     InitializeComponent(); 
     items.Add(new ABC 
     { 
      c0 = "1", 
      c1 = "DGH", 
      c2 = "yes" 
     }); 
     items.Add(new ABC 
     { 
      c0 = "2", 
      c1 = "ABC", 
      c2 = "no" 
     }); 
     items.Add(new ABC 
     { 
      c0 = "3", 
      c1 = "XYZ", 
      c2 = "yes" 
     }); 
    } 
} 
+0

排序? – 2013-03-17 07:15:14

+0

@AppDeveloper:我想按c1字段對此列表進行排序。你能幫我怎麼做嗎? – Sakura 2013-03-17 07:17:41

回答

5

如何:

var sortedItems = items.OrderBy(i => i.c1); 

這將返回IEnumerable<ABC>,如果你需要一個列表,添加ToList

List<ABC> sortedItems = items.OrderBy(i => i.c1).ToList(); 
2
List<ABC> _sort = (from a in items orderby a.c1 select a).ToList<ABC>(); 
1
.OrderBy(x => x.c1); 

(或.OrderByDescending

是的,LINQ使它很容易。

2

嘗試類似:在其領域的基礎

var sortedItems = items.OrderBy(itm => itm.c0).ToList(); // sorted on basis of c0 property 
var sortedItems = items.OrderBy(itm => itm.c1).ToList(); // sorted on basis of c1 property 
var sortedItems = items.OrderBy(itm => itm.c2).ToList(); // sorted on basis of c2 property 
+0

針對鏈接到您的答案的問題添加評論不具有建設性。請刪除此評論。 – ColinE 2013-03-17 07:25:37

相關問題