问题
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.
回答1:
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();
回答2:
Create the array only if coll
is not empty, so the other way round:
int[] data = null;
if(coll.Any()) data = coll.Select(s => s.x).ToArray();
回答3:
There's not a way to get Select
to return null, but if you don't want to create an additional array you could do:
var tmp = coll.Select(s => s.x);
int[] data = tmp.Any() ? tmp.ToArray() : null;
来源:https://stackoverflow.com/questions/28611083/linq-to-return-null-if-an-array-is-empty