Sort the list so that a specific value ends at the top

I have an Offer class that contains a registered category.

I want all offers of a certain category to appear on the top, and then all the others.

I tried this, but to no avail, what would you recommend?

 Offers = Offers.OrderBy(x => x.Category == "Corporate").ToList(); 
+7
source share
2 answers

When you order a boolean false (0), before true (1). To get the elements matching the first predicate first, you must reverse the sort order with OrderByDescending :

 Offers = Offers.OrderByDescending(x => x.Category == "Corporate").ToList(); 
+19
source

C # Language Specification 5.0 does not specify a byte representation for true and false . Therefore, it is better not to rely on the assumption that true seems to be 1 . In addition, the result of sorting by the boolean expression x.Category == "Corporate" not obvious, since true can be represented by a negative value. Therefore, I use the ternary operator to explicitly specify the sort value:

 Offers = Offers .OrderBy(x => x.Category == "Corporate" ? 0 : 1) .ThenBy(x => x.Category) .ThenBy(x => x.Date) // or what ever .ToList(); 
+10
source

All Articles