Sort a List so a specific value ends up on top

13,787

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(); 
Share:
13,787

Related videos on Youtube

Wesley
Author by

Wesley

Updated on June 04, 2022

Comments

  • Wesley
    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
      Wesley over 12 years
      It doesn't sort properly, it seems to still be in the original order.
  • BlueRaja - Danny Pflughoeft
    BlueRaja - Danny Pflughoeft over 12 years
    Uh, but this will reverse the order of everything else too. Try OrderBy(x => x.Category != "Corporate") instead.
  • Christoffer Lette
    Christoffer Lette over 12 years
    +1. And perhaps adding a ThenBy(x => x.Category) to sort the remaining offers by Category name..?
  • Anthony Pegram
    Anthony Pegram over 12 years
    I'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
    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
    BlueRaja - Danny Pflughoeft over 12 years
    Ah I see, I was misunderstanding the boolean argument