Jonas Stawski

Everything .NET and More

Multiple Order By in LINQ with extension methods

For some reason I am inclined to write LINQ expressions using the Extension Methods. You know the one that looks something like this:

Context.Products.Where(p => p.ProductID > 100).OrderBy(p => p.Description).ToList();

Well the other day I was in need to order by multiple columns and my first instinct was to use an && operator just like you do when you want to filter by more than one condition. Of course that did not work. After further investigation I found my answer. When you need to sort by multiple properties you have to use the ThenBy Extension method after using the OrderBy. So in the above LINQ Expression if we need to sort by CategoryID first and then by Description we would do it like this:

Context.Products.Where(p => p.ProductID > 100).OrderBy(p => p.CategoryID).ThenBy(p => p.Description).ToList();

Happy Programming!

Comments (9) -

There is also a ThenByDescending extension method. Very weird names, but cool implementation.

Reply

Thanks for the info

Reply

I found this incredibly stupid implementation. I should just be able to call .OrderBy as many times and it should honor the order. Instead it reverses the order, putting the first column last and vice versa. Pissed me off to no end. Now I have to keep track of whether i already ordered by something to know whether to use .orderby or .thenby which now makes my code twice as complicated. terrible decision by microsoft which now makes dynamic sorting just that much harder.

Reply

Peter Edwards
Peter Edwards

Thanks just what I needed.

Reply

It solved my problem. Thanks!

Reply

John Petersen
John Petersen

Anybody know if you can use ThenBy from the start ie. never call OrderBy, because that would maybe make JRod happier Smile Me too, btw.

Reply

white label seo
white label seo

Nice post. I like the way you start and then conclude your thoughts. Thanks for this information. I really appreciate your work, keep it up.

Reply

good!

Reply

granadaCoder
granadaCoder

Rock it dude!  Thanks.

Reply

Add comment

biuquote
Loading