Linq Order by a specific number first then show all rest in order

vts picture vts · Mar 29, 2012 · Viewed 36.3k times · Source

If i have a list of numbers:

1,2,3,4,5,6,7,8

and I want to order by a specific number and then show the rest. For example if i pick '3' the list should be:

3,1,2,4,5,6,7,8

Looking for linq and c#. Thank you

Answer

Tim Schmelter picture Tim Schmelter · Mar 29, 2012

You can use a comparison in OrderBy or ThenBy to perform a conditional sorting.

list.OrderByDescending(i => i == 3).ThenBy(i => i);

I use OrderByDescending because i want matching results first(true is "higher" than false).