Fraz Sundal
Fraz Sundal

Reputation: 10448

How to apply multiple orderby in linq query

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

Answers (5)

user111013
user111013

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

Steven
Steven

Reputation: 172606

var sortedCollection =
    from item in collection
    orderby item.Property1, item.Property2 descending, item.Property3
    select item;

Upvotes: 34

Adam Ralph
Adam Ralph

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

Tim Jarvis
Tim Jarvis

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

Kell
Kell

Reputation: 3317

should be simply a matter of stating

orderby x, y descending, z

see good old ms examples

Upvotes: 1

Related Questions