How to: Handle Null Values in Query Expressions (C# Programming Guide)

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 does not handle null values, a NullReferenceException will be thrown when you execute the query.

Example

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 == null ? null : 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 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 };
}

See Also

Reference

Nullable Types (C# Programming Guide)

Nullable<T>

Concepts

LINQ Query Expressions (C# Programming Guide)