LINQ Union Method

In LINQ, the Union method or operator combines multiple collections into a single collection and returns the resultant collection with unique elements.

 

Following is the pictorial representation of the LINQ union method.

 

LINQ Union Method with Example

 

The union method will combine the collections into a single collection and return unique elements by removing duplicate elements.

Syntax of LINQ union Method

Following is the syntax of using the union method to get unique elements from multiple collections.

 

C# Code

 

var result = count1.Union(count2);

VB.NET Code

 

Dim result = count1.Union(count2)

If you observe the above syntax, we combine two collections to get the result as a single collection using the union method.

Example of LINQ Union Method

Following is the example of using the LINQ union method.

 

C# Code

 

using System;
using System.Linq;

namespace Linqtutorials
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] count1 = { "UK", "Australia", "India", "USA" };
      string[] count2 = { "India", "Canada", "UK", "China" };
      var result = count1.Union(count2);
      foreach (var item in result)
      {
        Console.WriteLine(item);
      }
      Console.ReadLine();
    }
  }
}

VB.NET Code

 

Module Module1

Sub Main()
Dim count1 As String() = {"UK", "Australia", "India", "USA"}
Dim count2 As String() = {"India", "Canada", "UK", "China"}
Dim result = count1.Union(count2)
For Each item In result
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub
End Module

If you observe the above example, we are combining two collections, “count1” and “count2” using the union method to get unique elements from both collections.

Result of LINQ Union Method Example

Following is the result of the LINQ union method example.

 

UK
Australia
India
USA
Canada
China

This is how we can use the LINQ union method in c#, vb.net to get unique elements from collections.