LINQ to return null if array is empty

public class Stuff { public int x; // ... other stuff } 

I have an IEnumerable<Stuff> , and I want to build an int[] all x properties of all the Stuff objects in the collection.

I do:

 IEnumerable<Stuff> coll; // ... var data = coll.Select(s => sx).ToArray(); 

What I want is an empty array, not int[0] if the collection is empty. In other words, if !coll.Any() , then I want data = null . (My actual need is that coll be an intermediate result of a complex LINQ expression, and I would like to do this using the LINQ operation in the expression chain instead of storing the intermediate result)

I know that int[0] more in demand than null in many contexts, but I save many of these results and prefer to skip nulls than empty arrays.

So my current solution is something like:

 var tmp = coll.Select(s => sx).ToArray(); int[] data = tmp.Any() ? tmp : null; 

Any way to do this without saving tmp ?

EDIT . The main question is how to do this without preserving intermediate results. Something like NULLIF() from T-SQL , where you return what you passed if the condition is false, and null if the condition is true.

+5
source share
3 answers

If you do this a lot, you can 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 call code:

 var data = coll.Select(s => sx).ToArrayOrNull(); 
+11
source

Create an array only if coll not empty, so vice versa:

 int[] data = null; if(coll.Any()) data = coll.Select(s => sx).ToArray(); 
+2
source

It is not possible to get Select to return null, but if you do not want to create an additional array, you can do:

 var tmp = coll.Select(s => sx); int[] data = tmp.Any() ? tmp.ToArray() : null; 
+1
source

Source: https://habr.com/ru/post/1213741/


All Articles