Linq OrderByDescending, null first

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.


Solution 1:

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

Solution 2:

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.

Solution 3:

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.