Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I manage multiple OrderByDescending criteria?

Tags:

c#

linq

I want to get a list that order by three property that by priority is

  1. ToDate
  2. Number
  3. RunDate

My code is here

MyList
    .OrderByDescending(p => p.ToDate)
    .OrderByDescending(p => p.Number)
    .OrderByDescending(p => p.RunDate)
    .FirstOrDefault();

But the result is incorrect.

For example when MyList contains two elements: e1, e2 and e1.ToDate > e2.ToDate, the result is e2.

Which property should come first? The property with highest priority (ToDate) or lowest one (RunDate)?

like image 517
Omid-RH Avatar asked Jan 11 '11 13:01

Omid-RH


1 Answers

I suspect you really want:

MyList
.OrderByDescending(p => p.ToDate)
.ThenByDescending(p => p.Number)
.ThenByDescending(p => p.RunDate)
.FirstOrDefault();

ThenBy and ThenByDescending are used to specify secondary orderings after you've provided a primary one using OrderBy or OrderByDescending.

like image 101
Jon Skeet Avatar answered Nov 01 '22 13:11

Jon Skeet