21

I want to apply order by on multiple columns some ascending and others are in descending order in LINQ. How can i do that?

Old Pro
  • 24,624
  • 7
  • 58
  • 106
Fraz Sundal
  • 10,288
  • 22
  • 81
  • 132

5 Answers5

32
var sortedCollection =
    from item in collection
    orderby item.Property1, item.Property2 descending, item.Property3
    select item;
Steven
  • 166,672
  • 24
  • 332
  • 435
28

Borrowing from 101 LINQ Samples:

orderby p.Category, p.UnitPrice descending

or as a Lambda:

products.OrderBy(p => p.Category).ThenByDescending(p => p.UnitPrice); 
CokoBWare
  • 456
  • 3
  • 13
8

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)
Adam Ralph
  • 29,453
  • 4
  • 60
  • 67
  • Why would you want to do that? LINQ is much more readable than extension methods and lambda's. – Steven Jan 06 '11 at 12:39
  • 9
    I think it's a matter of preference. When reading/writing code I don't like having to make the context switch between method based C# code and declarative LINQ code. I find it easier to read and see what's going on when method chaining is used. Also, ultimately, the LINQ is converted to method calls by the compiler so I prefer to go straight to the horse's mouth and have my code more directly reflect the statements which are executed (JIT compiled) at runtime. – Adam Ralph Jan 06 '11 at 13:38
1

should be simply a matter of stating

orderby x, y descending, z

see good old ms examples

Kell
  • 3,252
  • 20
  • 19
0

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.

Tim Jarvis
  • 18,465
  • 9
  • 55
  • 92