Quantifiers in LINQ

by Sachin Singh


Posted on Saturday, 06 February 2021

Tags: Quantifiers in LINQ

Sometimes, we may need to check whether all, some, or at least one element in the collection satisfies a given condition or not, and then we proceed further. For example, if you have to check, whether any employee having a Salary less than 25K exist or not, then, with plain c#, you will have to iterate over the Employees collection and check each employee's Salary against the given condition, for such requirements we have quantifiers in Linq, which helps in deciding whether some, all or any element in the collection qualifies for a given condition or not.

All these methods return Boolean value i.e. True or False depending on whether if some or all of the elements in a collection satisfy a given condition.

There are three quantifiers in Linq, they are
    • All
    • Any
    • Contains

The following diagram shows more detailed information related to Quantifiers operators.

Linq Quantifiers
Quantifiers in Linq

All

It is used to check whether all elements in the collection satisfies a given condition or not. If all the elements in the collection satisfies the condition then it returns true otherwise false , this means, even one of the element fails to qualify the condition then the Any() operator will return false.

Example: Check all numbers in the List are even or not.

  var numbers = new List<int>(){ 28, 35, 68, 72, 98 };
            bool isAllEven = numbers.All(x => x % 2 == 0);
            Console.WriteLine(isAllEven);

Any

It is used to check whether at least one element in the collection satisfies a given condition or not. If none of the element in the collection qualifies the condition then it returns false otherwise it returns true.

Example: check whether an even number exist in the collection or not.

var numbers = new List<int>(){ 25, 35, 65, 75, 95 };
            bool isAllEven = numbers.Any(x => x % 2 == 0);
            Console.WriteLine(isAllEven);

Contains

It is used to check whether a specific element is present in the collection or not, if the specific element is present in the collection then the Contains() operator will return true otherwise it will return false.

Example: Whether "95" is present in the given list of integers or not.

   var numbers = new List<int>(){ 25, 35, 65, 75, 95 };
            bool isAllEven = numbers.Contains(95);
            Console.WriteLine(isAllEven);

In the coming chapters, we will discuss all these LINQ Quantifiers in detail with examples.