开发者

How can I manage multiple OrderByDescending criteria?

开发者 https://www.devze.com 2023-02-04 03:01 出处:网络
I want to get a list that order by three property that by priority is ToDate Number RunDate My code is here

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.Numbe开发者_运维知识库r)
    .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)?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消