Any <t> </t>的反方法是什么

时间:2012-01-05 11:06:49

标签: c# linq

如果集合中不包含对象,我该如何检查Linq。 I.E.与Any<T>相反。

我可以用!反转结果但是为了便于阅读,我想知道是否有更好的方法来做到这一点?我应该自己添加扩展吗?

4 个答案:

答案 0 :(得分:77)

您可以轻松创建None扩展方法:

public static bool None<TSource>(this IEnumerable<TSource> source)
{
    return !source.Any();
}

public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    return !source.Any(predicate);
}

答案 1 :(得分:54)

验证任何(至少一个)记录是否与某个标准匹配的相反方法是验证所有记录与标准不匹配。

你没有发布你的完整例子,但如果你想要的是相反的东西:

var isJohnFound = MyRecords.Any(x => x.FirstName == "John");

您可以使用:

var isJohnNotFound = MyRecords.All(x => x.FirstName != "John");

答案 2 :(得分:2)

当我想知道某个集合是否包含一个对象但是我想要检查集合中的所有对象是否与给定对象匹配时,找到此线程标准。我最终做了这样的检查:

var exists = modifiedCustomers.Any(x => x.Key == item.Key);

if (!exists)
{
    continue;
}

答案 3 :(得分:1)

除了添加的答案之外,如果您不想包装Any()方法,可以按如下方式实施None()

public static bool None<TSource>(this IEnumerable<TSource> source) 
{
    if (source == null) { throw new ArgumentNullException(nameof(source)); }

    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        return !enumerator.MoveNext();
    }
}

public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null) { throw new ArgumentNullException(nameof(source)); }
    if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); }

    foreach (TSource item in source)
    {
        if (predicate(item))
        {
            return false;
        }
    }

    return true;
}

除了无参数重载之外,您还可以应用ICollection<T>优化,这在LINQ实现中实际上不存在。

ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null) { return collection.Count == 0; }
相关问题