An < T > 的相反方法是什么

如果一个集合不包含一个对象,我如何用 Linq 进行检查。

我可以用 !反转结果,但是为了可读性,我想知道是否有更好的方法来做到这一点?我应该自己加上延期吗?

30902 次浏览

You can easily create a None extension method:

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

The opposite of verifying that any (at least one) record matches a certain criteria would be verifying that all records do not match the criteria.

You didn't post your full example, but if you wanted the opposite of something like:

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

You could use:

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

In addition to the answers added, if you don't want to wrap Any() method you can implement None() as follows:

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

In addition to that for the parameterless overload you can apply ICollection<T> optimization, which actually does not exist in LINQ implemenetation.

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

Found this thread when I wanted to find out if a collection does not contain one object but I do not want to check that all objects in a collection match the given criteria. I ended up doing a check like this:

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


if (!exists)
{
continue;
}