Linq OrderByDescending, null first

C#Linq

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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.

Solution 4 - C#

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;

Solution 5 - C#

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontofutimView Question on Stackoverflow
Solution 1 - C#Frédéric HamidiView Answer on Stackoverflow
Solution 2 - C#ZachView Answer on Stackoverflow
Solution 3 - C#JonView Answer on Stackoverflow
Solution 4 - C#andrewView Answer on Stackoverflow
Solution 5 - C#tom noblemanView Answer on Stackoverflow