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();
When you order by a boolean value
false
(0) comes beforetrue
(1). To get the elements that match the predicate first you should reverse the sort order by usingOrderByDescending
:The C# Language Specification 5.0 does not specify a byte representation for the
true
andfalse
values. Therefore, it is better to not rely on the assumption thattrue
is represented by1
. Also, the result of sorting by the Boolean expressionx.Category == "Corporate"
is not obvious, astrue
could be represented by a negative value as well. Therefore, I use a ternary operator to explicitly specify a sort value: