C# LINQ Quantifier Operators : Any, All and Contains

Updated on     Kisan Patel

The Quantifier operators return a Boolean value if the elements of the sequence satisfy a specific condition.

The clauses that are classified as the Quantifier operators are Any, All, and Contains.

LINQ All Operator

All determines if every member satisfies the condition. This clause enumerates the source sequence and returns True if no elements fails the test passed by the query. The All clause return a True value for an empty sequence.

NorthwindEntities _db = new NorthwindEntities();
bool hasCustomers = _db.Customers.All(x => x.Country == "USA");
//hasCustomers = false

LINQ Any Operator

Any returns a Boolean value indicating whether any or more members satisfy condition.

For Example,

NorthwindEntities _db = new NorthwindEntities();
bool hasCustomers = _db.Customers.Any(x => x.Country == "USA");
//hasCustomers = true

The Any clause return false value for an empty sequence.

Hint: It’s almost never a good idea to use a query like

// Don't use this 
if (query.Count() != 0)

So use “Any” instead as follows

// Use this instead 
if (query.Any())

LINQ Contains Operator

The Contains clause determines whether a sequence contains the specified element. The Contains clause checks the source sequence to determine if it contains the specified element. When the matching element is found, the Contains clause returns the result.

int[] digits = { 2, 4, 6, 8, 10 };
bool hasEight = digits.Contains(8); // return true

C# LINQ

Leave a Reply