OrderBy with boolean value | How to put specific values on top of the list


Blog

Hi there!

I’ve just had to sort some list alphabetically with specific values on top. Here is one of the possible solution.

Worth to know:

  • OrderBy sorts items in ascending order [a, b, c, d] [1,2,3,4]
  • Can be use with boolean function
  • False = 0
  • True = 1

So if we use:


list.OrderBy(item => item == "Cat");

Item that equals „Cat” will be placed as last element, because as the only element returns true(1) as a result + as it was mention before OrderBy sort items in ascending order, so other items different then „Cat” will return false(0), so they will be first on the list.

Solution

Then if we want to place some element on the top of the list just use OrderByDescending.
Below example orders list alphabetically but at the first place „Lion”, second „Cat” and then rest items are sort alphabetically.
It’s important to use ThenBy for next statement instead of OrderBy because OrderBy overrides and ThenBy adds to previous statement.

You can check the code example using LinqPad, just paste it as C# statement and run.

var list = new List<string> () { "Dog", "Cat", "Mouse", "Elephant"};

list.Add("Lion");
list.Add("Rabbit");

list = list.OrderByDescending(item => item == "Lion")
.ThenByDescending(item => item == "Cat")
.ThenBy(item => item)
.ToList();

list.Dump();

Best regards!