如何根据对象的属性对列表进行排序

如何根据对象的属性对列表进行排序

问题描述:

如何使用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

如何:

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

这将返回IEnumerable<ABC>,如果你需要一个列表,添加ToList

List<ABC> sortedItems = items.OrderBy(i => i.c1).ToList(); 

List<ABC> _sort = (from a in items orderby a.c1 select a).ToList<ABC>(); 

.OrderBy(x => x.c1); 

(或.OrderByDescending

是的,LINQ使它很容易。

尝试类似:在其领域的基础

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