Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to return null if an array is empty

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.

like image 556
David Chappelle Avatar asked Feb 19 '15 16:02

David Chappelle


People also ask

Does LINQ where return null or empty list?

It will return an empty enumerable. It won't be null.

Is it better to return empty array or null?

Empty collection. Always. It is considered a best practice to NEVER return null when returning a collection or enumerable.

What does the LINQ first operator return when used against an empty sequence?

If the collection is empty, it will return one element with the value of 0 and then the sum will be applied.


1 Answers

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();
like image 152
Matthew Watson Avatar answered Sep 28 '22 08:09

Matthew Watson