Most Common LINQ Methods: Concat, Distinct, Except, Intersect and Union Explained
Tags: dotnet, programming, webdev, softwaredevelopment
Published: 2024-01-15 17:57:52

## Enter the world of LINQ with this comprehensive guide. Discover in-depth explanations of highly popular LINQ methods such as **Concat**, **Distinct**, **Except**, **Intersect **and **Union**.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibjm37jftxszw17wc7o3.png)

### 1.Concat Method:

_Concatenate Collections with LINQ_

This method, enabling developers to merge two or more collections effortlessly. Whether you’re dealing with arrays, lists, or any other collection type, the LINQ Concat method provides a concise and efficient way to unite them.

Concat method code example:

```
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list1 = new List<int> { 1, 2, 3 };
        List<int> list2 = new List<int> { 3, 4, 5 };
        List<int> list3 = new List<int> { 5, 6, 7 };

        var concatenatedList = list1.Concat(list2).Concat(list3);
      
        // Apply Distinct to remove duplicates.
        var distinctList = concatenatedList.Distinct();

        // Print the concatenated integers (with duplicates).
        Console.WriteLine("Concatenated Integers (with Duplicates):");
        foreach (var number in concatenatedList)
        {
            Console.WriteLine(number);
        }

        //Expected outputs for concatenatedList elements:
          Concatenated Integers (with Duplicates):
          1
          2
          3
          3
          4
          5
          5
          6
          7

        // Print the distinct integers (without duplicates).
        Console.WriteLine("Distinct Integers:");
        foreach (var number in distinctList)
        {
            Console.WriteLine(number);
        }

        //Expected outputs for concatenatedList elements:
          Distinct Integers:
          1
          2
          3
          4
          5
          6
          7
    }
}
```
The first list example is the lists without removing duplicates. We can remove duplicates and set a unique lists with using **Distinct** method.

### 2.Distinct Method:
_Using LINQ Distinct for Unique Values_

This method is a designed to eliminate duplicate elements from a collection, leaving you with a distinct set of values. This operation is particularly valuable when you’re dealing with data that may contain redundant entries, and you want to streamline your dataset for analysis, reporting, or further processing.

Distinct method code example:

```
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5, 5 };

        var distinctNumbers = numbers.Distinct();

        Console.WriteLine("Original Numbers:");
        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nDistinct Numbers:");
        foreach (var number in distinctNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

//Excepted output:
Original Numbers:
1
2
2
3
4
4
5
5

Distinct Numbers:
1
2
3
4
5
```

### 3.Except Method:
_Subtracting Collections with LINQ Except_

This method is designed for subtracting one collection from another, allowing you to obtain the elements that exist in the first collection but are absent in the second.

Except method code example:

```
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> firstNumbers = new List<int> { 1, 2, 2, 3, 4, 4, 5, 5 };
        List<int> secondNumbers = new List<int> { 3, 4, 5, 5, 6, 7, 7 };

        var difference = firstNumbers.Except(secondNumbers);

        Console.WriteLine("First Numbers:");
        Console.WriteLine(string.Join(", ", firstNumbers));

        Console.WriteLine("\nSecond Numbers:");
        Console.WriteLine(string.Join(", ", secondNumbers));

        Console.WriteLine("\nDifference (Unique to First):");
        Console.WriteLine(string.Join(", ", difference));
    }
}

//Excepted output:
First Numbers:
1, 2, 2, 3, 4, 4, 5, 5

Second Numbers:
3, 4, 5, 5, 6, 7, 7

Difference (Unique to First):
1, 2
```

### 4.Intersect Method:
_Finding Common Elements with LINQ Intersect_

This method is designed for identifying and extracting common elements shared between two collections. It allows you to pinpoint the elements that exist in both the first and second collections, providing a streamlined way to find intersections or matches.

Intersect method code example:

```
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> firstNumbers = new List<int> { 1, 2, 2, 3, 4, 4, 5, 5 };
        List<int> secondNumbers = new List<int> { 3, 4, 5, 5, 6, 7, 7 };

        var commonElements = firstNumbers.Intersect(secondNumbers);

        Console.WriteLine("First Numbers:");
        Console.WriteLine(string.Join(", ", firstNumbers));

        Console.WriteLine("\nSecond Numbers:");
        Console.WriteLine(string.Join(", ", secondNumbers));

        Console.WriteLine("\nCommon Elements:");
        Console.WriteLine(string.Join(", ", commonElements));
    }
}

//Excepted output:
First Numbers:
1, 2, 2, 3, 4, 4, 5, 5

Second Numbers:
3, 4, 5, 5, 6, 7, 7

Common Elements:
3, 4, 5
```

### 5.LINQ Union Method

_Combining Collections with LINQ Union_

This method is designed for combining and merging multiple collections into a single collection. It allows you to unify the elements from two or more collections while ensuring that each unique element appears only once in the resulting sequence. This operation is particularly valuable when you need to create a combined dataset or a list of distinct values from multiple sources.

Union method code example:

```
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> firstNumbers = new List<int> { 1, 2, 2, 3, 4, 4, 5, 5 };
        List<int> secondNumbers = new List<int> { 3, 4, 4, 5, 5, 6, 7, 7 };
        List<int> thirdNumbers = new List<int> { 5, 5, 6, 7, 7, 8, 9, 10 };

        var mergedList = firstNumbers.Union(secondNumbers).Union(thirdNumbers);

        Console.WriteLine("First Numbers:");
        Console.WriteLine(string.Join(", ", firstNumbers));

        Console.WriteLine("\nSecond Numbers:");
        Console.WriteLine(string.Join(", ", secondNumbers));

        Console.WriteLine("\nThird Numbers:");
        Console.WriteLine(string.Join(", ", thirdNumbers));

        Console.WriteLine("\nMerged List (Distinct Elements):");
        Console.WriteLine(string.Join(", ", mergedList));
    }
}

//Excepted output:
First Numbers:
1, 2, 2, 3, 4, 4, 5, 5

Second Numbers:
3, 4, 4, 5, 5, 6, 7, 7

Third Numbers:
5, 5, 6, 7, 7, 8, 9, 10

Merged List (Distinct Elements):
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
```

As you can see, the LINQ Union method effectively combines and merges lists with duplicate elements into a single list containing all unique elements.

Thank you for reading.

Hope it is helpful.

[Linkedin](https://tr.linkedin.com/in/erdogancanyuksel)