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

时间:2013-03-17 07:14:35

标签: c# list sorting

如何按List<ABC>元素对此c1进行升序排序?非常感谢你!

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"
        });
    }
}

4 个答案:

答案 0 :(得分:5)

这个怎么样:

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

这会返回IEnumerable<ABC>,如果您需要列表,请添加ToList

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

答案 1 :(得分:2)

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

答案 2 :(得分: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

答案 3 :(得分:1)

.OrderBy(x => x.c1);

(或.OrderByDescending

是的,LINQ让事情变得那么容易。

相关问题