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

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


当前回答

我用的是这个:

    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) 
}

其他回答

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

我用简单的if来检查它

看看我的解决方案

foreach (Pet pet in v.Pets)
{
    if (pet == null)
    {
        Console.WriteLine(" No pet");// enumerator is empty
        break;
    }
    Console.WriteLine("  {0}", pet.Name);
}

我的做法是,利用一些现代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()

它为null将返回true

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

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

            return true;
        }
   
    }

代码

没有自定义助手,我也推荐?.Any() ??. any () == true相对简洁,只需要指定一次序列。


当我想要像对待空集合一样对待一个缺失的集合时,我使用以下扩展方法:

public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
{
    return sequence ?? Enumerable.Empty<T>();
}

这个函数可以与所有LINQ方法和foreach组合,而不仅仅是. any(),这就是为什么我更喜欢它而不是人们在这里提出的更专业的帮助函数。