C#

Using Quantifiers in LINQ

Programmingempire

In this article, I will explain how to use Quantifiers in LINQ. Basically quantifiers are operators that return a boolean value. Further, these quantifier operators return a value that indicates whether all elements in a set satisfy a particular condition or only few. Also, whether a specific element is available in the set. Accordingly, the LINQ in C# provides following quantifiers.

  • All
  • Any
  • Contains

The All Quantifier

Basically, the All quantifier performs a check on all the elements of a sequence for the specified condition. Accordingly, it returns a boolean value of true or false depending on whether the given condition is satidfied or not.

The Any Quantifier

Similarly, the Any quantifier also performs a check on all of the elements of the sequence for the specified condition. However, it returns true, if any one element of the sequence satisfies the condition. Otherwise, it returns false.

The Contains Quantifier

In contrast ot All, and Any, the Contains quantifier returns true if the given element is present in the sequence. Therefore, the Contains quantifier doesn’t check for any condition. But, it checks for the presence of a specific element in the sequence.

Example Demonstrating the Use of Quantifiers in LINQ

The following code shows an example that describes how we can use the quantifiers on a collection of user-defined types. As can be seen in the code, we create the array using the instances of class Orders. Further, the field items in the class Orders represents the sequence. In other words, the quantifiers are evaluated on the items array for each element of the orders_array collection.

Once, we have created our collection, we formulate a LINQ query that takes the whole collection as the data source. Further, for each element of the data dource that is represented by the range-variable ob, a specific quantifer is applied on its items member. Also, the All, and Any quantifiers take a lambda expression as the parameter. Hence, we can use these lambda expression to specify the condition. Accordingly, an element of the items array will return true or false depending on whether it starts with the letter ‘p‘ or not. Accordingly, we get the output as shown below.

While, the first query results in a single record, the second one retrieved the four records. Likewise, the last query retrieves all records which contain ‘pendrive’ item.

using System;
using System.Linq;
namespace QuantifiersExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Orders[] orders_array = new Orders[]
            {
                new Orders{order_id=1, items=new string[]{"pendrive", "phonecover", "usbcable", "powerbank" }, total=1750},
                new Orders{order_id=2, items=new string[]{"trousers", "curtains", "pendrive", "pen", "marker", "crayon" }, total=4233},
                new Orders{order_id=3, items=new string[]{"pen", "pencil", "pendrive", "powerbank", "phone", "pedegree", "plate" }, total=14670},
                new Orders{order_id=4, items=new string[]{"trousers", "top" }, total=1023},
                new Orders{order_id=5, items=new string[]{"umbrella", "raincoat", "bag" }, total=1567},
                new Orders{order_id=6, items=new string[]{"dress" }, total=2567},
                new Orders{order_id=7, items=new string[]{"laptop" }, total=45567},
                new Orders{order_id=8, items=new string[]{"backpack", "handbag" }, total=3200},
                new Orders{order_id=9, items=new string[]{"grocery", "perfumes", "dress", "handbag" }, total=6789},
                new Orders{order_id=10, items=new string[]{"nailcutter", "handcreme", "bag" }, total=1200},
            };


            var q1 = from ob in orders_array
                     where ob.items.All(x => x.StartsWith('p'))
                     select ob;

            Console.WriteLine("All orders where item name starts with the letter 'p'...");
            foreach(Orders ob in q1)
            {
                Console.Write($"Order ID: {ob.order_id}, Items: ");
                foreach (String s in ob.items)
                    Console.Write(s + " ");
                Console.Write($", Total: {ob.total}");
                Console.WriteLine();
            }
            Console.WriteLine();

            var q2 = from ob in orders_array
                     where ob.items.Any(x => x.StartsWith('p'))
                     select ob;

            Console.WriteLine("Any orders where item name starts with the letter 'p'...");
            foreach (Orders ob in q2)
            {
                Console.Write($"Order ID: {ob.order_id}, Items: ");
                foreach (String s in ob.items)
                    Console.Write(s + " ");
                Console.Write($", Total: {ob.total}");
                Console.WriteLine();
            }
            Console.WriteLine();

            var q3 = from ob in orders_array
                     where ob.items.Contains("pendrive")
                     select ob;

            Console.WriteLine("All orders containing pendrive...");
            foreach (Orders ob in q3)
            {
                Console.Write($"Order ID: {ob.order_id}, Items: ");
                foreach (String s in ob.items)
                    Console.Write(s + " ");
                Console.Write($", Total: {ob.total}");
                Console.WriteLine();
            }
            Console.WriteLine();

        }
    }
    class Orders
    {
        public int order_id;
        public String[] items;
        public int total;
    }
}

Output

Example of Using Quantifiers in LINQ
Example of Using Quantifiers in LINQ

Further Reading

Selection Sort in C#

Insertion Sort in C#

Bubble Sort in C#

How to Create Instance Variables and Class Variables in Python

Comparing Rows of Two Tables with ADO.NET

Example of Label and Textbox Control in ASP.NET

One Dimensional and Two Dimensuonal Indexers in C#

Private and Static Constructors in C#

Methods of Array Class

Anonymous Functions in C#

Programs to Find Armstrong Numbers in C#

Matrix Multiplication in C#

One Dimensional and Two Dimensional Indexers in C#

Static Class Example in C#

Rotating an Array in C#

Generic IList Interface and its Implementation in C#

Recursive Binary search in C#

C# Practice Questions

Creating Navigation Window Application Using WPF in C#

Find Intersection Using Arrays

An array of Objects and Object Initializer

Performing Set Operations in LINQ

Using Quantifiers in LINQ

Data Binding Using BulletedList Control

Grouping Queries in LINQ

Generic Binary Search in C#

Understanding the Quantifiers in LINQ

Join Operation using LINQ

Deferred Query Execution and Immediate Query Execution in LINQ

Examples of Query Operations using LINQ in C#

An array of Objects and Object Initializer

Language-Integrated Query (LINQ) in C#

How Data Binding Works in WPF

Examples of Connected and Disconnected Approach in ADO.NET

New Features in C# 9

IEnumerable and IEnumerator Interfaces

KeyValuePair and its Applications

C# Root Class – Object

Access Modifiers in C#

Learning Properties in C#

Learning All Class Members in C#

Examples of Extension Methods in C#

How to Setup a Connection with SQL Server Database in Visual Studio

Understanding the Concept of Nested Classes in C#

LINQ To SQL Examples

A Beginner’s Tutorial on WPF in C#

Explaining C# Records with Examples

Everything about Tuples in C# and When to Use?

Creating Jagged Arrays in C#

Linear Search and Binary search in C#

Learning Indexers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Basic Examples

IEqualityComparer Interface

programmingempire

You may also like...