Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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

~Nate�

___________________________________________

Please use the [vb]/[cs] tags on posted code.

Please post solutions you find somewhere else.

Follow me on Twitter here.

  • Administrators
Posted
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 ;)

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted
Yes, I saw a few articles using Lambda -- for some reason I couldn't get them to compile against my List<T>.

~Nate�

___________________________________________

Please use the [vb]/[cs] tags on posted code.

Please post solutions you find somewhere else.

Follow me on Twitter here.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...