Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you do custom sorting in LINQ with null always on the end?

Tags:

c#

linq

I need to sort in memory lists of strings or numbers in ascending or descending order. However, the list can contain null values and all null values must appear after the numbers or strings.

That is the input data might be:

1, 100, null, 5, 32.3

The ascending result would be

1, 5, 32.3, 100, null

The descending list would be

100, 32.3, 5, 1, null

Any ideas on how to make this work?

like image 534
Jerryk Avatar asked Jul 02 '10 06:07

Jerryk


1 Answers

I don't have a compiler in front of me to check, but I'm thinking something like:

x.OrderBy(i => i == null).ThenBy(i => i)
like image 107
Ken Avatar answered Oct 25 '22 20:10

Ken