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.
It will return an empty enumerable. It won't be null.
Empty collection. Always. It is considered a best practice to NEVER return null when returning a collection or enumerable.
If the collection is empty, it will return one element with the value of 0 and then the sum will be applied.
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();
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