如何检查 IEnumerable 是 null 还是空? [英] How to check if IEnumerable is null or empty?

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

问题描述

我喜欢 string.IsNullOrEmpty 方法.我很想拥有一些可以为 IEnumerable 提供相同功能的东西.有这样的吗?也许一些收集助手类?我问的原因是,在 if 语句中,如果模式是 (mylist != null && mylist.Any()),代码看起来很混乱.使用 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?.

推荐答案

当然你可以写:

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

但是,请注意并非所有序列都是可重复的;通常我更喜欢只走一次,以防万一.

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

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

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