如何检查IEnumerable是null还是空? [英] How to check if IEnumerable is null or empty?
问题描述
我喜欢 string.IsNullOrEmpty
方法。我喜欢有一些东西,将允许相同的功能IEnumerable。有这样吗?也许有一些收集帮助类?我要求的原因是在如果
语句代码看起来杂乱,如果模式(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?.
推荐答案
b
$ b
Sure you could write that:
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屋!