Any, All, Contains: The boolean quantifiers
On this page
Logical Checks
Sometimes you don't need the data; you just need to know if the data Exists or if it Complies with a rule.
1. Any: Existence Check
Checks if a sequence contains ANY elements. **Architect Tip:** Always prefer .Any() over .Count() > 0. Any() returns true as soon as it finds the first match (Short-circuiting), whereas Count() must enumerate the entire list to find the total before comparing.
2. All: Complete Compliance
Returns true ONLY if every single element in the sequence matches the predicate. This is excellent for validation logic (e.g., 'Ensure all line items have a positive price').
3. Contains: Value Matching
Checks if a specific object or value exists in the sequence. For objects, this uses Equality Comparers. **Tip:** In EF Core, list.Contains(id) is translated into a SQL IN (...) clause, which is highly efficient for bulk lookups.
3. Architect Insight
Q: "Should I check for null before using Any()?"
Architect Answer: "Yes. LINQ methods are extension methods, but they will still throw a NullReferenceException if the source collection itself is null. Use the null-conditional operator: myList?.Any() == true to safely check without crashing."