LINQ to return null if an array is empty
c#, linq, linq-to-objects
Solution
If you're doing this a lot, you could write an extension method:
public static class IEnumerableExt
{
public static T[] ToArrayOrNull<T>(this IEnumerable<T> seq)
{
var result = seq.ToArray();
if (result.Length == 0)
return null;
return result;
}
}
Then your calling code would be:
var data = coll.Select(s => s.x).ToArrayOrNull();
Problem
``` public class Stuff { public int x; // ... other stuff } ``` I have a `IEnumerable<Stuff>` and I want to build a `int[]` of all of the `x` properties of all the `Stuff` objects in the collection. I do: ``` IEnumerable<Stuff> coll; // ... var data = coll.Select(s => s.x).ToArray(); ``` What I want is a null array rather than a `int[0]` if the collection is empty. In other words, if `!coll.Any()`, then I want `data = null`. (My actual need is that `coll` is an intermediate result of a complex LINQ expression, and I would like to do this with a LINQ operation on the expression chain, rather than saving the intermediate result) I know that `int[0]` is more desirable than `null` in many contexts, but I am storing many of these results and would prefer to pass around `nulls` than empty arrays. So my current solution is something like: ``` var tmp = coll.Select(s => s.x).ToArray(); int[] data = tmp.Any() ? tmp : null; ``` Any way to do this without storing `tmp`? EDIT: The main question is how to do this without storing intermediate results. Something like `NULLIF()` from `T-SQL` where you get back what you passed in if the condition is false, and `NULL` if the condition is true.