What is the opposite Any <T> method
How can I check with Linq if the collection does not contain an object. I.E. The opposite of Any<T> .
I could invert the result with ! but for readability I wondered if there was a more efficient way to do this? Should I add the extension myself?
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 meets a specific criterion will verify that all records do not meet the criteria.
You did not provide your complete example, but if you would like to contrast something like:
var isJohnFound = MyRecords.Any(x => x.FirstName == "John"); You can use:
var isJohnNotFound = MyRecords.All(x => x.FirstName != "John"); In addition to the added answers, if you do not want to use the 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, for seamless overload, you can apply the ICollection<T> optimization, which does not actually exist in the LINQ implementation.
ICollection<TSource> collection = source as ICollection<TSource>; if (collection != null) { return collection.Count == 0; } I found this thread when I wanted to find out if one team does not contain one object, but I do not want to check that all objects in the collection meet the specified criteria. I ended up doing the check as follows:
var exists = modifiedCustomers.Any(x => x.Key == item.Key); if (!exists) { continue; }