Handle null values in query expressions

This example shows how to handle possible null values in source collections. An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null, and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query.

You can code defensively to avoid a null reference exception as shown in the following example:

var query1 =
    from c in categories
    where c != null
    join p in products on c.ID equals p?.CategoryID
    select new
    {
        Category = c.Name,
        Name = p.Name
    };

In the previous example, the where clause filters out all null elements in the categories sequence. This technique is independent of the null check in the join clause. The conditional expression with null in this example works because Products.CategoryID is of type int?, which is shorthand for Nullable<int>.

In a join clause, if only one of the comparison keys is a nullable value type, you can cast the other to a nullable value type in the query expression. In the following example, assume that EmployeeID is a column that contains values of type int?:

void TestMethod(Northwind db)
{
    var query =
        from o in db.Orders
        join e in db.Employees
            on o.EmployeeID equals (int?)e.EmployeeID
        select new { o.OrderID, e.FirstName };
}

In each of the examples, the equals query keyword is used. You can also use pattern matching, which includes patterns for is null and is not null. These patterns aren't recommended in LINQ queries because query providers may not interpret the new C# syntax correctly. A query provider is a library that translates C# query expressions into a native data format, such as Entity Framework Core. Query providers implement the System.Linq.IQueryProvider interface to create data sources that implement the System.Linq.IQueryable<T> interface.

See also