Sort a List so a specific value ends up on top

2020-06-09 05:44发布

I have a class Offer which contains a filed Category.

I want all Offers of a specific category to appear on top, followed by all else.

I tried this, but to no avail, what would you recommend?

Offers = Offers.OrderBy(x => x.Category == "Corporate").ToList();

2条回答
对你真心纯属浪费
2楼-- · 2020-06-09 06:22

When you order by a boolean value false (0) comes before true (1). To get the elements that match the predicate first you should reverse the sort order by using OrderByDescending:

Offers = Offers.OrderByDescending(x => x.Category == "Corporate").ToList();
查看更多
看我几分像从前
3楼-- · 2020-06-09 06:38

The C# Language Specification 5.0 does not specify a byte representation for the true and false values. Therefore, it is better to not rely on the assumption that true is represented by 1. Also, the result of sorting by the Boolean expression x.Category == "Corporate" is not obvious, as true could be represented by a negative value as well. Therefore, I use a ternary operator to explicitly specify a sort value:

Offers = Offers
    .OrderBy(x => x.Category == "Corporate" ? 0 : 1)
    .ThenBy(x => x.Category)
    .ThenBy(x => x.Date) // or what ever
    .ToList(); 
查看更多
登录 后发表回答