Linq method to convert zeros to empty IEnumerable <T>?

I am dealing with some arrays that return to me from a third-party API. Sometimes they return as null . I know how to elegantly handle LINQ except zero. 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); 

Using a coalescence operator is not much. Am I missing something from LINQ that handles this?

+8
c # linq ienumerable
source share
4 answers

This is actually the same solution you have, but I am using the extension method.

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

So, in the end we get:

 IEnumerable<Thing> procs = APICall(foo, bar); var result = from proc in procs.EmptyIfNull() where proc != null select Transform(proc); 
+11
source share

You can simply 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 coalescence outside the linq expression, which makes the code more rigid.

You can also just skip the whole linq expression by doing a conditional check on nonnull.

+2
source share

why not use something more efficient, for example:

 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); 
+1
source share

Linq expects ienumerable something, even if it is empty. Perhaps you can try moving the coalition after calling the api?

0
source share

All Articles