February 27, 2020

Using the LINQ OrderBy operator with null values

This blog post demonstrates a quick tip for sorting values in ascending order when some of the values can potentially be NULL.

Let’s assume you have an application that allows users to capture installation dates for customers. Our simplified Installation class may look something like the following.

public class Installation
    public string Customer { get; set; }

    public int Id { get; set; }

    public DateTime? InstallationDate { get; set; }

Let us further assume that you want to display a list of all upcoming installations for a user, with the earliest upcoming installations showing first. In some instances, the data may not have a valid installation date defined yet as we have not arranged the installation date with the user. In this case, the value of the InstallationDate property is null.

Your first thought is probably to use the LINQ OrderBy operator, so given a list of upcoming installations we can do the following:

var orderedInstallations = installations
    .OrderBy(i => i.InstallationDate);

The problem with this is that it sorts all the null values at the beginning of the list, as you can see in the sample console output below.

Installations ordered by date with null values at the top

We want to display the installations without a confirmed installation date to the user, but we want to show them at the end of the list so that the user can see the confirmed upcoming installations first.

The solution to this is quite simple. We first sort by the InstallationData.HasValue property in descending order, and then by the InstallationDate, for example:

var orderedInstallations = installations
    .OrderByDescending(i => i.InstallationDate.HasValue)
    .ThenBy(i => i.InstallationDate);

With this simple change, the confirmed installations display first, and then the unconfirmed ones following them:

Installations ordered by date with null values at the bottom

I have put together a sample console application demonstrating this that you can find at https://github.com/jerriepelser-blog/orderby-with-null-values. In the case of my demo app, I operate on in-memory lists, but this technique works when using LINQ with EF Core against a database as well.