Sort a List so a specific value ends up on top
Solution 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();
Solution 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();
Related videos on Youtube
Wesley
Updated on June 04, 2022Comments
-
Wesley almost 2 years
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 over 12 yearsIt doesn't sort properly, it seems to still be in the original order.
-
-
BlueRaja - Danny Pflughoeft over 12 yearsUh, but this will reverse the order of everything else too. Try
OrderBy(x => x.Category != "Corporate")
instead. -
Christoffer Lette over 12 years+1. And perhaps adding a ThenBy(x => x.Category) to sort the remaining offers by Category name..?
-
Anthony Pegram over 12 yearsI'm hesitant to rely upon the ordering of false and true and that other developers would understand it. I'm inclined to make my intent absolutely clear, such as
.OrderBy(x => x.Category == "Corporate" ? 0 : 1)
. -
phoog over 12 years@BlueRaja-DannyPflughoeft the order of everything else will be undefined (if OrderBy uses an unstable sort, which I think it does).
-
BlueRaja - Danny Pflughoeft over 12 yearsAh I see, I was misunderstanding the boolean argument