Reputation: 10448
I want to apply order by on multiple columns some ascending and others are in descending order in LINQ. How can i do that?
Upvotes: 21
Views: 29795
Reputation:
Borrowing from 101 LINQ Samples:
orderby p.Category, p.UnitPrice descending
or as a Lambda:
products.OrderBy(p => p.Category).ThenByDescending(p => p.UnitPrice);
Upvotes: 28
Reputation: 172606
var sortedCollection =
from item in collection
orderby item.Property1, item.Property2 descending, item.Property3
select item;
Upvotes: 34
Reputation: 29956
Steven's answer will work, but I prefer method chaining to declarative LINQ syntax, e.g.
collection
.OrderBy(e => e.Property1)
.ThenByDescending(e => e.Property2)
.ThenBy(e => e.Property3)
Upvotes: 10
Reputation: 18815
For completeness and as an alternative to the other good answers here...
There is also an overload or OrderBy that takes an IComparer, if this is a common order pattern that you want, then you might like to create a class that imlements that and pass it to the orderby clause, let it handle the more complex ordering, that way its re-usable for when ever you are ordering your query the same way.
Upvotes: 0