我喜欢绳子。IsNullOrEmpty方法。我想有一些东西,将允许相同的功能IEnumerable。有这样的东西吗?也许是一些收集助手类?我问的原因是,在if语句中,如果模式是(mylist != null && mylist. any()),代码看起来很混乱。使用Foo.IsAny(myList)会干净得多。

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


当前回答

Jon Skeet的回答(https://stackoverflow.com/a/28904021/8207463)有一个很好的方法,使用扩展方法- Any()为NULL和EMPTY。但是他正在验证问题的所有者,以防NOT NULL。 因此,请仔细更改Jon验证AS NULL的方法为:

If (yourList?.Any() != true) 
{
     ..your code...
}

不使用(将不验证为NULL):

If (yourList?.Any() == false) 
{
     ..your code...
}

你也可以在验证AS NOT NULL的情况下(没有测试,只是作为例子,但没有编译器错误)做一些类似使用predicate的事情:

If (yourList?.Any(p => p.anyItem == null) == true) 
{
     ..your code...
}

https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0

你可以使用哪个.NET版本,请检查:

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-4.8#moniker-applies-to

其他回答

只需添加使用系统。Linq和看到魔术发生时,你试图访问可用的方法在IEnumerable。添加它将使您能够访问名为Count()的方法,就像这样简单。只要记住在调用count():)之前检查空值即可。

我也遇到过同样的问题,我是这样解决的:

    public bool HasMember(IEnumerable<TEntity> Dataset)
    {
        return Dataset != null && Dataset.Any(c=>c!=null);
    }

“c = > c !=null"将忽略所有null实体。

public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {
    return enumerable == null || !enumerable.Any();
}

它为null将返回true

enter    public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
    {

        try
        {
            return enumerable?.Any() != true;
        }
        catch (Exception)
        {

            return true;
        }
   
    }

代码

我用的是这个:

    public static bool IsNotEmpty(this ICollection elements)
    {
        return elements != null && elements.Count > 0;
    }

埃杰姆:

List<string> Things = null;
if (Things.IsNotEmpty())
{
    //replaces ->  if (Things != null && Things.Count > 0) 
}