What is the opposite method of Any<T>
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");
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;
}
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; }