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

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


当前回答

它为null将返回true

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

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

            return true;
        }
   
    }

代码

其他回答

我使用

    list.Where (r=>r.value == value).DefaultIfEmpty().First()

如果不匹配,结果将为空,否则返回其中一个对象

如果您想要列表,我相信离开First()或调用ToList()将提供列表或null。

这可能会有所帮助

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

它为null将返回true

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

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

            return true;
        }
   
    }

代码

当然你可以这样写:

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

但是,要注意不是所有序列都是可重复的;一般来说,我宁愿只遛一次,以防万一。

 public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source != null && source.Any();
    }

我自己的扩展方法来检查非空和任何