C#

Using Quantifiers in LINQ

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *