Linq OrderByDescending, but keep a null value first

I have a set of integers that I want to order in descending order, with the exception of storing the value 0, as the first in the list.

For example: 0,1,2,3,4,5,6,7,8

The following should appear: 0.8,7,6,5,4,3,2,1

Thanks!

+4
source share
1 answer
var input = new [] {0,1,2,3,4,5,6,7,8}; 

Two sorts that work with both negative and positive numbers:

 var result = input.OrderBy(i => i == 0? 0 : 1).ThenByDescending(i => i); 

or this if all your numbers are non-negative:

 var result = input.OrderByDescending(i => i == 0? int.MaxValue : i); 

or some really weird solution if you have negative and positive numbers, but you don't want to sort twice (as I do in the first solution):

 var result = input .GroupBy(i => i == 0 ? 0 : 1) .OrderBy(g => g.Key) .Select(g => g.Key == 0 ? g : g.OrderByDescending(i => i) .SelectMany(g => g); 
+8
source

Source: https://habr.com/ru/post/1344102/


All Articles