How to Use LINQ All in C# for Condition Checks
Use
LINQ All in C# to check if every element in a collection meets a specific condition by passing a predicate function. It returns true if all elements satisfy the condition, otherwise false.Syntax
The All method is called on a collection and takes a predicate function as a parameter. This function defines the condition to check for each element.
collection.All(element => condition)collection: The list or array to check.element: Each item in the collection.condition: A boolean expression that must be true for all elements.
csharp
bool result = collection.All(element => element > 0);Example
This example shows how to use All to check if all numbers in an array are positive.
csharp
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 2, 4, 6, 8 }; bool allPositive = numbers.All(n => n > 0); Console.WriteLine($"Are all numbers positive? {allPositive}"); int[] mixedNumbers = { 2, -4, 6, 8 }; bool allPositiveMixed = mixedNumbers.All(n => n > 0); Console.WriteLine($"Are all numbers positive in mixed array? {allPositiveMixed}"); } }
Output
Are all numbers positive? True
Are all numbers positive in mixed array? False
Common Pitfalls
Common mistakes when using All include:
- Passing a predicate that always returns
trueorfalsewithout checking elements. - Using
Allon an empty collection, which returnstrueby default (because no elements violate the condition). - Confusing
AllwithAny, which checks if any element meets the condition.
csharp
using System; using System.Linq; class Program { static void Main() { int[] empty = { }; // This returns true because no elements violate the condition bool allPositiveEmpty = empty.All(n => n > 0); Console.WriteLine($"All positive in empty array? {allPositiveEmpty}"); // Wrong: predicate always true int[] numbers = { 1, 2, 3 }; bool wrongCheck = numbers.All(n => true); Console.WriteLine($"Wrong check (always true): {wrongCheck}"); } }
Output
All positive in empty array? True
Wrong check (always true): True
Quick Reference
LINQ All Method Summary:
- Returns
trueif all elements satisfy the condition. - Returns
truefor empty collections. - Requires a predicate function.
- Useful for validating all items in a list.
Key Takeaways
Use
All to check if every element in a collection meets a condition.All returns true for empty collections by default.Pass a clear predicate function that returns a boolean for each element.
Do not confuse
All with Any which checks if any element matches.Common mistake: using a predicate that always returns true or false without logic.