Nate Bross Posted June 10, 2008 Posted June 10, 2008 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. var items = from item i in items where i.Property.Contains("value") orderby i.AnotherProperty descending select i If you use a gridview you can't 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. 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 Quote ~Nate� ___________________________________________ Please use the [vb]/[cs] tags on posted code. Please post solutions you find somewhere else. Follow me on Twitter here.
Administrators PlausiblyDamp Posted June 10, 2008 Administrators Posted June 10, 2008 http://mironabramson.com/blog/post/2008/05/Sorting-a-collection-using-sort-expression-string.aspx has a nice way of doing this using lambda expression trees rather than reflection - not a clue if it is better or worse but it has nice buzz words in the article and has worked for me in the past ;) Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Nate Bross Posted June 11, 2008 Author Posted June 11, 2008 Yes, I saw a few articles using Lambda -- for some reason I couldn't get them to compile against my List<T>. Quote ~Nate� ___________________________________________ Please use the [vb]/[cs] tags on posted code. Please post solutions you find somewhere else. Follow me on Twitter here.
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.