score:183

Accepted answer

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

score:0

Take a look at David Oesterreich's blog:

var queryResult =
orderedProducts from enumerableProducts
order by orderedProducts.ProductName,
orderedProducts.Price != null ? 1 : 0 descending,
orderedProducts.Price
select orderedProducts;

score:0

like the accepted version above but with syntax for c# v6

tickets.OrderByDescending(x => x?.Erstellt ?? DateTime.Now)

score: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.

score:34

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.


Related Query