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

Published by boczek on

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.


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 = list.OrderByDescending(item => item == "Lion")
.ThenByDescending(item => item == "Cat")
.ThenBy(item => item)


Best regards!

1 Comment

al · 18/02/2021 at 1:11 PM

Thank you 🙂

Leave a Reply

Your email address will not be published.