C# LINQ Any and All Operators Explained
In C# LINQ, Any and All are quantifier
operators used to validate collections against specified conditions by
returning a boolean result. While Any checks whether at
least one element in a sequence meets a condition (or simply checks if a
collection contains any elements), All verifies whether
every single element satisfies a given predicate. This article provides
a clear breakdown of how both operators function, their performance
advantages such as short-circuit evaluation, and practical code examples
demonstrating their use.
The LINQ Any Operator
The Any operator determines whether any element in a
collection matches a provided condition, or whether a collection
contains any elements at all. It returns true if it finds
at least one matching element; otherwise, it returns
false.
Any has two primary overloads:
- Parameterless
Any(): Returnstrueif the collection contains at least one item, regardless of its value. This is more efficient than checkingcollection.Count() > 0onIEnumerable<T>because it does not need to enumerate the entire collection. - Predicate-based
Any(predicate): Evaluates each element against a specified condition until a match is found.
List<int> numbers = new List<int> { 3, 5, 8, 9 };
// Checks if the list has any elements
bool hasElements = numbers.Any(); // Returns true
// Checks if any element is even
bool hasEvenNumber = numbers.Any(n => n % 2 == 0); // Returns trueThe LINQ All Operator
The All operator checks whether all elements in a
collection satisfy a specified condition. It returns true
only if every element matches the criteria; otherwise, it returns
false. Unlike Any, the All
operator requires a predicate.
List<int> numbers = new List<int> { 2, 4, 6, 8 };
// Checks if all elements are even
bool allEven = numbers.All(n => n % 2 == 0); // Returns true
// Checks if all elements are greater than 5
bool allGreaterThanFive = numbers.All(n => n > 5); // Returns falseShort-Circuit Evaluation
Both Any and All utilize short-circuit
evaluation to optimize performance:
Anyshort-circuits ontrue: As soon as it encounters the first element that satisfies the predicate, it stops enumerating the sequence and immediately returnstrue.Allshort-circuits onfalse: As soon as it encounters the first element that fails the predicate, it stops enumerating and immediately returnsfalse.
This behavior makes both operators highly efficient on large collections or unbounded sequences, as they rarely need to process the entire collection unless the condition demands it.
Behavior on Empty Collections
Understanding how these operators handle empty sequences is essential to prevent logic bugs:
Any()on an empty collection always returnsfalsebecause there are no elements to satisfy the condition.All()on an empty collection always returnstrue. This follows the mathematical principle of vacuous truth: because there are zero elements in the collection, there is no element that violates the condition.