Wesley
Wesley

Reputation: 5621

Sort a List so a specific value ends up on top

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

Upvotes: 18

Views: 16055

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112502

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

Upvotes: 21

Mark Byers
Mark Byers

Reputation: 838666

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

Upvotes: 41

Related Questions