C#

Performing Set Operations in LINQ

In this article, I will explain how to perform Set Operations in LINQ. Basically, Language Integrated Query (LINQ) has several query methods for performing set operations such as union, intersection, and set difference.

Query Methods for Performing Set Operations in LINQ

The following section provides a description of query methods available in LINQ. In fact, we can represent a set using a collection such as an array.

In order to find the union of two sets, we can use the Union() method, which returns a set of unique elements which are available in either of the two sets. Similarly, the Intersect() method returns the set intersection comprising of the common elements in the two sets. Likewise, the Except() method returns a set difference, comprising of all the elements present in one set which are not available in the second set. Also, there is a Distinct() method that returns unique values from a set.

Examples of Set Operations in LINQ

The following code shows how to use the Union(), Except(), and Intersect() methods in a query.

using System;
using System.Linq;
namespace LINQSetOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] Things = {"Cart", "Umbrella", "Refrigerator", "Humidifier", "Fan", "Light", "Pump", "Playground", "Shop", "School", "Chair" };
            String[] RoomThings = { "Fan", "Light", "Bed", "Almirah", "Refrigerator", "Humidifier", "Chair"};

            Console.WriteLine("Elements of Set 1 (Things): ");
            foreach (String s in Things)
                Console.Write(s + " ");
            Console.WriteLine();

            Console.WriteLine("Elements of Set 2 (RoomThings): ");
            foreach (String s in RoomThings)
                Console.Write(s + " ");
            Console.WriteLine();

            var q1 = (from a1 in Things
                      select a1).Union(RoomThings);
            Console.WriteLine("Union of two sets...");
            foreach (String s in q1)
                Console.Write(s + " ");
            Console.WriteLine();

            var q2 = (from a1 in Things
                      select a1).Intersect(RoomThings);
            Console.WriteLine("Intersection of two sets...");
            foreach (String s in q2)
                Console.Write(s + " ");
            Console.WriteLine();

            var q3 = (from a1 in Things
                      select a1).Except(RoomThings);
            Console.WriteLine("Difference of two sets...");
            foreach (String s in q3)
                Console.Write(s + " ");
            Console.WriteLine();

        }
    }
}

Output

Demonstrating Union, Intersection, and Difference Set Operations in LINQ
Demonstrating Union, Intersection, and Difference Set Operations in LINQ

Apart from the above operations, there is also a Distinct() method that returns unique values from a set. The following example shows how the Distinct() method works.

using System;
using System.Linq;
namespace DistinctMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = {1,2,2,1,1,1,1,3,4,1,2,3,3,4,7,5,6,6,5,8,9,12,14,15,1,2,8,5,70,5,5,6,16 };
            Console.WriteLine("All Elements in the Set...");
            foreach (int i in arr)
                Console.Write(i + " ");
            Console.WriteLine();

            Console.WriteLine("Distinct Elements in the Set...");
            var q = arr.Distinct();
            foreach (int i in q)
                Console.Write(i + " ");
            Console.WriteLine();
        }
    }
}

Output

Distinct() Method in LINQ
Distinct() Method in LINQ



Further Reading

A Beginner’s Tutorial on WPF in C#

Everything about Tuples in C# and When to Use?

Linear Search and Binary Search in C#

Creating Jagged Arrays in C#

When should We Use Private Constructors?

C# Practice Questions

C# Basic Examples

Private and Static Constructors in C#

Constructors in C#

C# Arrays

C# Examples

How to Create a C# Console Application

Creating Navigation Window Application Using WPF in C#

LINQ To SQL Examples

Understanding the Concept of Nested Classes in C#

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

C# Root Class – Object

KeyValuePair and its Applications

IEnumerable and IEnumerator Interfaces

IEqualityComparer Interface

New Features in C# 9

Generic IList Interface and its Implementation in C#

Examples of Connected and Disconnected Approach in ADO.NET

How Data Binding Works in WPF

Language-Integrated Query (LINQ) in C#

Examples of Query Operations using LINQ in C#

Join Operation using LINQ

Deferred Query Execution and Immediate Query Execution in LINQ

Understanding the Quantifiers in LINQ

Grouping Queries in LINQ

Generic Binary Search in C#

Recursive Binary Search in C#

Leave a Reply

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