Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq OrderByDescending but keep zero value first

Tags:

linq

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

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

Should result in: 0,8,7,6,5,4,3,2,1

Thanks!

like image 444
Mike Cole Avatar asked Dec 28 '22 23:12

Mike Cole


1 Answers

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

Two sortings which 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 both negative and positive numbers but you don't want to sort twice (as I'm doing in 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);
like image 110
Snowbear Avatar answered May 12 '23 10:05

Snowbear