17

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();
Wesley
  • 5,381
  • 9
  • 42
  • 65

2 Answers2

38

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();
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
20

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(); 
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188