对其中一个对象的属性排序对象列表

时间:2013-12-17 12:40:02

标签: c# .net list sortedlist

我有一个对象列表List<MyObject>,我希望根据MyObject的一个属性对此列表进行排序。所以,例如

MyObject obj1, obj2, obj3 = new MyObject();
obj1.Value = 0.2;
obj2.Value = 2.2;
obj3.Value = 1.3;

.. List&lt;&gt;的顺序会是

List[0] = obj2;
List[1] = obj3;
List[2] = obj1;

我可以使用.NET本机功能执行此操作,还是必须编写自己的搜索?

3 个答案:

答案 0 :(得分:5)

1选项OrderBy

yourList = yourList.OrderBy(x=>x.PropertyName).ToList();

yourList = yourList.OrderByDescending(x=>x.PropertyName).ToList();

2选项List.Sort

yourList.Sort((x,y)=>x.PropertyName.CompareTo(y.PropertyName));

yourList.Sort((x,y)=>-x.PropertyName.CompareTo(y.PropertyName));

答案 1 :(得分:2)

使用OrderBy

var ordered = list.OrderBy(v => v.Value).ToList();

还有OrderByDescending

答案 2 :(得分:1)

您应首先为对象定义array并尝试此

 MyObject[] myObjList = new MyObject[]{obj1,Obj2,Obj3};   
    var myRes =myObjList.OrderByDescending(obj => obj.Value);