In LINQ, the Union method or operator is used to combine multiple collections into a single collection and return resultant collection with unique elements.
Following is the pictorial representation of the LINQ union method.
The union method will combine both the collections into a single collection and return unique elements from the collections by removing duplicate elements.
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 are combining two collections to get the result as a single collection using 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 ModuleIf you observe above example we are combining two collections “count1”, “count2” using union method to get only unique elements from both the collections.
Following is the result of 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.