Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a List so a specific value ends up on top

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();
like image 672
Wesley Avatar asked Dec 08 '11 19:12

Wesley


People also ask

How do you sort a list with specific value in Python?

sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order. sort() accepts two optional parameters. reverse is the first optional parameter.

How do you sort a list in custom order in Python?

Using sort(), lamba, index(): The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.

How do you sort a list according to another list?

Approach : Zip the two lists. Create a new, sorted list based on the zip using sorted(). Using a list comprehension extract the first elements of each pair from the sorted, zipped list.


1 Answers

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();
like image 178
Mark Byers Avatar answered Sep 17 '22 15:09

Mark Byers