Sort a List so a specific value ends up on top

2020-06-09 05:55发布

问题:

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();

回答1:

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();


回答2:

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();