Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq method to transform nulls into empty IEnumerable<T>?

I'm dealing with some arrays that are being returned to me from a 3rd party API. Sometimes these come back as null. I am able to handle everything elegantly with LINQ except for the null case. I came up with something like this:

IEnumerable<Thing> procs = APICall(foo, bar);
var result = from proc in procs ?? Enumerable.Empty<Thing>()
    where proc != null
    select Transform(proc);

The use of the coalescing operator here chafes a little. Am I missing something from LINQ that handles this?

like image 523
recursive Avatar asked May 24 '11 19:05

recursive


People also ask

How do you handle null values in LINQ query?

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. var query1 = from c in categories where c !=

How do I empty my IEnumerable?

Clear() will empty out an existing IEnumerable. model. Categories = new IEnumerable<whatever>() will create a new empty one. It may not be a nullable type - that would explain why it can't be set to null.

How do I return empty IEnumerable?

Empty<T> actually returns an empty array of T (T[0]), with the advantage that the same empty array is reused. Note that this approach is not ideal for non-empty arrays, because the elements can be modified (however an array can't be resized, resizing involves creating a new instance).


1 Answers

This is in effect the same solution that you have, but I use an extension method.

public static partial class EnumerableExtensions
{
    public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
    {
        return source ?? Enumerable.Empty<T>();
    }
}

So that we end up with:

IEnumerable<Thing> procs = APICall(foo, bar);
var result = from proc in procs.EmptyIfNull()
             where proc != null
             select Transform(proc);
like image 112
Reddog Avatar answered Oct 15 '22 21:10

Reddog