Yannis Yannis - 1 year ago 112
C# Question

IQueryable order by two or more properties

I am currently ordering a list of custom objects using the IQueryable OrderBy method as follows:


Now I am looking to sort by more than one property. Is there any way to do that?


Answer Source
OrderBy(i => i.PropertyName).ThenBy(i => i.AnotherProperty)

In OrderBy and ThenBy you have to provide keySelector function, which chooses key for sorting from object. So if you know property name only at runtime then you can make such function with Reflection like:

var propertyInfo = i.GetType().GetProperty("PropertyName"); 
var sortedList = myList.OrderBy(i => propertyInfo.GetValue(i, null)) 

But it will be slower, then direct access to property. Also you can "compile" such function on the fly with Linq.Expressions and it will work faster than reflection but it is not very easy. Or you can use CollectionViewSource and their sorting ablilities in WPF.

And don't forget that OrderBy() returns sorted enumerable and it does not sort your existed List inplace. In your example you did not save sorted list to variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download