recursive
recursive

Reputation: 86134

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?

Upvotes: 11

Views: 4304

Answers (4)

Simon Stender Boisen
Simon Stender Boisen

Reputation: 3431

You could just write the following:

IEnumerable<Thing> procs = APICall(foo, bar) ?? Enumerable.Empty<Thing>();

var result = from proc in procs
    where proc != null
    select Transform(proc);

This way you move the coalescing outside the linq expression which makes the code look more tight.

You could also just skip the linq expression entirely by doing an conditional check on nonnull.

Upvotes: 2

Tomasz Mikuś
Tomasz Mikuś

Reputation: 136

why not use something more efficient like:

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

Upvotes: 1

Jay
Jay

Reputation: 6294

Linq expects an ienumerable of something, even if it is empty. Perhaps you can try moving the coalescing to after the api call?

Upvotes: 0

Reddog
Reddog

Reputation: 15579

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);

Upvotes: 14

Related Questions