我喜欢绳子。IsNullOrEmpty方法。我想有一些东西,将允许相同的功能IEnumerable。有这样的东西吗?也许是一些收集助手类?我问的原因是,在if语句中,如果模式是(mylist != null && mylist. any()),代码看起来很混乱。使用Foo.IsAny(myList)会干净得多。
这篇文章没有给出答案:IEnumerable是空的?
我喜欢绳子。IsNullOrEmpty方法。我想有一些东西,将允许相同的功能IEnumerable。有这样的东西吗?也许是一些收集助手类?我问的原因是,在if语句中,如果模式是(mylist != null && mylist. any()),代码看起来很混乱。使用Foo.IsAny(myList)会干净得多。
这篇文章没有给出答案:IEnumerable是空的?
当前回答
下面是@Matt Greer的有用答案的修改版本,它包括一个静态包装器类,这样你就可以将它复制粘贴到一个新的源文件中,不依赖于Linq,并添加了一个泛型IEnumerable<T>重载,以避免非泛型版本会发生的值类型装箱。[编辑:注意,使用IEnumerable<T>并不能阻止对枚举器进行装箱,鸭子类型不能阻止这一点,但至少值类型集合中的元素不会每个都被装箱。]
using System.Collections;
using System.Collections.Generic;
public static class IsNullOrEmptyExtension
{
public static bool IsNullOrEmpty(this IEnumerable source)
{
if (source != null)
{
foreach (object obj in source)
{
return false;
}
}
return true;
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
if (source != null)
{
foreach (T obj in source)
{
return false;
}
}
return true;
}
}
其他回答
当然你可以这样写:
public static class Utils {
public static bool IsAny<T>(this IEnumerable<T> data) {
return data != null && data.Any();
}
}
但是,要注意不是所有序列都是可重复的;一般来说,我宁愿只遛一次,以防万一。
我的做法是,利用一些现代c#特性:
选择1)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any() ?? false);
}
}
选择2)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any()).GetValueOrDefault();
}
}
顺便说一下,永远不要使用Count == 0或Count() == 0来检查一个集合是否为空。总是使用Linq的.Any()
if (collection?.Any() == true){
// if collection contains more than one item
}
if (collection?.Any() != true){
// if collection is null
// if collection does not contain any item
}
我使用Bool IsCollectionNullOrEmpty = !(Collection?. any ()??false);。希望这能有所帮助。
分解:
. any()如果Collection为空将返回null,如果Collection为空则返回false。
收集? .Any () ?如果Collection为空,则返回false;如果Collection为空,则返回false。
它的补将得到IsEmptyOrNull。
这可能会有所帮助
public static bool IsAny<T>(this IEnumerable<T> enumerable)
{
return enumerable?.Any() == true;
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
return enumerable?.Any() != true;
}