Useful "dynamic" LINQ Query

Nate Bross

Well-known member
Joined
Apr 6, 2005
Messages
601
Location
Chicago, IL
So I was trying to use the orderby method in LINQ to sort some data. It requires the actual property name to use so you end up with code like this.
C#:
var items = from item i in items
     where i.Property.Contains("value")
     orderby i.AnotherProperty descending
     select i
If you use a gridview you cant use the e.SortExpression to dynamically sort. unless you write a LINQ query for each possible column.

So after huting around on the internet, I ended up with this, which allows you to dynamically sort based on object property names.
C#:
var items = from item i in items
     where i.Property.Contains("value")
     orderby i.GetType().InvokeMember("SortProperty", System.Reflection.BindingFlags.GetProperty, null, i, null) descending
     select i
 
Back
Top