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();
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With