如何检查是否IEnumerable的为空或空? [英] How to check if IEnumerable is null or empty?

查看:1593
本文介绍了如何检查是否IEnumerable的为空或空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我爱 string.IsNullOrEmpty 方法。我很想有一些会允许IEnumerable的相同的功能。有没有这样的?也许有的收集辅助类?我问的原因是,在如果语句code看起来杂乱,如果图案是(mylist中= NULL和放大器;!&安培; mylist中。任何())。这将是更清洁的有 Foo.IsAny(myList上)

I love string.IsNullOrEmpty method. I'd love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection helper class? The reason I am asking is that in if statements the code looks cluttered if the patter is (mylist != null && mylist.Any()). It would be much cleaner to have Foo.IsAny(myList).

这篇文章没有给出这个问题的答案:?。 IEnumerable的是空

This post doesn't give that answer: IEnumerable is empty?.

摘要: 请参阅下面的答案可能的解决方法。

SUMMARY: Please see answers below for possible workarounds.

推荐答案

当然您可以写:

public static class Utils {
    public static bool IsAny<T>(this IEnumerable<T> data) {
        return data != null && data.Any();
    }
}

不过,要小心,不是所有的序列是重复的; 一般的我preFER只能走他们一次,以防万一。

however, be cautious that not all sequences are repeatable; generally I prefer to only walk them once, just in case.

这篇关于如何检查是否IEnumerable的为空或空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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