What is the purpose of "All" operator in LINQ?
The correct purpose of the All
operator in LINQ is to determine whether all elements in a sequence (collection) satisfy a specified condition. The All
operator evaluates the condition for each element in the sequence and returns a boolean value of true
if the condition is true for all elements. If any element fails to satisfy the condition, the operator returns false
.
Here's the syntax of the All
operator in LINQ:
bool result = sequence.All(element => condition);
-
sequence
represents the collection or sequence of elements that you want to evaluate.
element => condition
is a lambda expression or delegate that specifies the condition to evaluate for each element in the sequence.
Example:
int[] numbers = { 1, 2, 3, 4, 5 };
bool allEven = numbers.All(num => num % 2 == 0);
// allEven = false, as not all numbers in the sequence are even
In this example, the All
operator is used to check if all numbers in the numbers
array are even. The lambda expression num => num % 2 == 0
is the condition to be evaluated for each element. Since the array contains odd numbers as well, the result is false
.
The All
operator is useful when you need to verify that a certain condition holds true for every element in a collection. It provides a convenient way to perform checks on all elements without requiring manual iteration or additional logic.