如果数组为空,LINQ返回null [英] LINQ to return null if an array is empty

查看:54
本文介绍了如果数组为空,LINQ返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有一个IEnumerable<Stuff>,我想为该集合中所有Stuff对象的所有x属性的所有int[]属性构建一个int[].

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.

我愿意

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

如果集合为空,我想要的是一个空数组,而不是一个int[0].换句话说,如果是!coll.Any(),那么我要data = null. (我的实际需求是coll是复杂LINQ表达式的中间结果,我想通过表达式链上的LINQ操作来做到这一点,而不是保存中间结果)

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)

我知道在许多情况下int[0]null更可取,但是我存储了许多结果,并且比空数组更愿意传递nulls.

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;

是否可以在不存储tmp的情况下执行此操作?

Any way to do this without storing tmp?

编辑:主要问题是如何在不存储中间结果的情况下执行此操作.像T-SQL中的NULLIF()一样,如果条件为false,则可以获取传入的内容;如果条件为true,则可以获取NULL的内容.

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.

推荐答案

如果您经常这样做,则可以编写扩展方法:

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();

这篇关于如果数组为空,LINQ返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆