Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq OrderByDescending, null first

Tags:

c#

linq

I have a field in my database that holds a DateTime?. I would like to sort the results so that the NULLs show up at the top, then descending by DateTime, e.g.,

null
null
2012-04-01
2012-01-01
2011-09-04

The reason is that I am looking at expiration dates, though some entries do not expire.

like image 229
tofutim Avatar asked Sep 03 '11 05:09

tofutim


3 Answers

You can return DateTime.MaxValue instead of null from the ordering expression, so rows with null dates are sorted first:

yourData.OrderByDescending(row => row.dateTimeField ?? DateTime.MaxValue);
like image 134
Frédéric Hamidi Avatar answered Oct 23 '22 03:10

Frédéric Hamidi


I find the most straightforward approach to be:

data.OrderBy(Function(o) o.myDate IsNot Nothing).ThenByDescending(Function(o) o.myDate)

in C# I think...

data.OrderBy(o => o.myDate != null).ThenByDescending(o => o.myDate)

This will also work with LINQ to SQL. I'm not sure if if(nullable, value) will successfully translate to SQL.

like image 34
Zach Avatar answered Oct 23 '22 02:10

Zach


You could try something like this:

var nulls = table.Where(x => x.NullableDateTimeField == null);
var notNulls = table.Where(x => x.NullableDateTimeField != null);

var result = nulls.Concat(notNulls.OrderByDescending(x => x.NullableDateTimeField));

It's more "obviously correct" than "likely to be super-efficient", but it's at least a starting point.

like image 3
Jon Avatar answered Oct 23 '22 03:10

Jon