Sorting C# nullable DateTime columns by nulls followed by DateTime descending

Friday, October 2, 2015
by Sean McAlinden

I recently had to sort a column of DateTime values by nulls followed by DateTime descending.

The usecase was listing a users work employment history with most recent first.

The EndDate column was used for ascertaining the main sort order however this posed a problem with current jobs as they do not yet have an end date.

Luckily achieving this with Lambda (or linq) is very straight forward.

The following code simply uses DateTime.MaxValue if the actual DateTime is null:

var sortedJobs = Jobs.OrderByDescending(x => x.EndDate ?? DateTime.MaxValue);

And there you have it, the dataset is now sorted by nulls first then by DateTime descending.

If you wanted to add more logic to further enrich the sort you could simply add more sorting logic... the following includes the addition of a secondary sort on the jobs start date:

var sortedJobs = Jobs
    .OrderByDescending(x => x.EndDate ?? DateTime.MaxValue)
    .ThenByDescending(x => x.StartDate);

Lambda makes usecases like this so much easier to implement.