Mike Cole
Mike Cole

Reputation: 14713

Linq OrderByDescending but keep zero value first

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!

Upvotes: 4

Views: 2067

Answers (1)

Snowbear
Snowbear

Reputation: 17274

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);

Upvotes: 10

Related Questions