I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC"))
for ordering. Unfortunately, the method included only works on IQueryable<T>
. Is there any way to get this functionality on IEnumerable<T>
?
C# – Dynamic LINQ OrderBy on IEnumerable / IQueryable
cienumerableiqueryablelinqlinq-to-objects
Related Topic
- .net – the difference between IQueryable
and IEnumerable - Linq – Multiple “order by” in LINQ
- C# – Using IQueryable with Linq
- C# – Returning IEnumerable
vs. IQueryable - C# – LINQ OrderBy with more than one field
- C# – IEnumerable vs List – What to Use? How do they work
- C# – LINQ Orderby Descending Query
- C# – Group by in LINQ
Best Answer
Just stumbled into this oldie...
To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties.
To get it working with
IEnumerable<T>
you could add some wrapper methods that go viaAsQueryable
- but the code below is the coreExpression
logic needed.Edit: it gets more fun if you want to mix that with
dynamic
- although note thatdynamic
only applies to LINQ-to-Objects (expression-trees for ORMs etc can't really representdynamic
queries -MemberExpression
doesn't support it). But here's a way to do it with LINQ-to-Objects. Note that the choice ofHashtable
is due to favorable locking semantics: