WhereNotNull Extension Method

It’s not uncommon to write code similar to the following:

var result = source.Where(x => x != null).Select(x => x.Something);

While it doesn’t save a lot of typing, it’s convenient to define the following new extension method for IEnumerable<T>:

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> source)
    where T : class
{
    return source.Where(x => x != null);
}

If T were a nullable type, the example code would need to have a seemingly-unnecessary Nullable<T>.Value property access:

var result = source.Where(x => x != null).Select(x => x.Value.Something);

Additionally, tools like ReSharper will give a spurious “Possible ‘System.InvalidOperationException’” warning on the .Value access, because they can’t (currently) infer that all items will have a value.

If we create an overload of WhereNotNull that transforms IEnumerable<T?> to IEnumerable<T>, we solve both these problems:

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source)
    where T : struct
{
    foreach (T? t in source)
    {
        if (t.HasValue)
            yield return t.Value;
    }
}

Now, the example code looks the same, whether source is a sequence of reference types or nullable value types:

var result = source.WhereNotNull().Select(x => x.Something);

(Full source code for this post is available in EnumerableUtility.cs.)

Posted by Bradley Grainger on April 21, 2010