I've been running into situations where I feel I'm lacking a LINQ extension method which effectivelly checks if there is no match of the specified predicate in a collection. There is Any
and All
, but if I for instance use the following code:
if (Objects.All(u => u.Distance <= 0))
This returns true if all the objects in the collection are 0 or less yards away.
if (Objects.Any(u => u.Distance <= 0))
This returns true if there is at least one object in the collection which is 0 or less yards away from me.
So far so good, both those methods make sense and the syntax for them makes sense too. Now, if I want to check if there is no object with 0 or less distance, I'd have to invert the predicate inside the All
method to >= 0
instead of <= 0
or call !All()
, which in some cases results in very poorly readable code.
Is there no method which effectively does Collection.None(u => u.Distance <= 0)
to check if there is no object in the collection which is 0 or less yards away? It's syntactic sugar more than an actual problem, but I just have the feeling it's missing.
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
The Linq All Operator in C# is used to check whether all the elements of a data source satisfy a given condition or not. If all the elements satisfy the condition, then it returns true else return false. There is no overloaded version is available for the All method.
The Any method checks whether any of the element in a sequence satisfy a specific condition or not. If any element satisfy the condition, true is returned. Let us see an example. int[] arr = {5, 7, 10, 12, 15, 18, 20};
All() determines whether all elements of a sequence satisfy a condition. Any() determines whether any element of a sequence satisfies the condition.
None
is the same as !Any
, so you could define your own extension method as follows:
public static class EnumerableExtensions { public static bool None<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return !source.Any(predicate); } }
You can write your own Extension Method
:
public static bool None(this IEnumerable<T> collection, Func<T, bool> predicate) { return collection.All(p=>predicate(p)==false); }
Or on IQueryable<T>
as well
public static bool None(this IQueryable<T> collection, Expression<Func<TSource, bool>> predicate) { return collection.All(p=> predicate(p)==false); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With