C#

Performing Set Operations in LINQ

Programmingempire

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

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...