我有一个对象列表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本机功能执行此操作,还是必须编写自己的搜索?
答案 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)
答案 2 :(得分:1)
您应首先为对象定义array
并尝试此
MyObject[] myObjList = new MyObject[]{obj1,Obj2,Obj3};
var myRes =myObjList.OrderByDescending(obj => obj.Value);