I am writing a list sorting extension method.
My input is the list and a string with property name and sort direction.
This string can have multiple properties like so:
“Name ASC, Date DESC” etc.
I already implemented the string parsing and used reflection to get the property itself from the string, but what I am stuck on now is how do I dynamically chain the orderby methods.
something like:
_list.orderBy(x=>x.prop1).thenBy(x=>x.prop2) etc.
Is there any way to build this dynamically?
Use reflection to get from the string property names to a PropertyInfo’s. You can then build an expression tree using the PropertyInfo’s to dynamically construct all the orderbys. Once you have the expression tree, compile it to a delegate, (say Func, IEnumerable>) Pass in your _list parameter to this delegate and it will give you the ordered result as another enumerable.
To get the reflection information for the generic method on Enumerable, have a look at the answer on this post:
Get a generic method without using GetMethods
The result of the sample as shown in LinqPad