Question

I have a list of objects List<MyObject> and I want to have this list sorted based on one of the properties of MyObject. So, for example

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

..the order of the List<> would be

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

Can I do this using .NET native functions or must I write my own search?

Was it helpful?

Solution

1 Option OrderBy

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

descending

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

2 Option List.Sort

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

descending

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

OTHER TIPS

Use OrderBy:

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

There's also OrderByDescending.

you should define an array for your objects first and try this

 MyObject[] myObjList = new MyObject[]{obj1,Obj2,Obj3};   
    var myRes =myObjList.OrderByDescending(obj => obj.Value);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top