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?
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 !=
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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With