LINQ Union Method

  Total Views : 160
  Comments : 0
 
  Keywords : Linq union operator with example in c# / vb.net, How to use linq union method with two lists in c# / vb.net example, Linq union method to get unique elements from sequence in c# / vb.net

Here we will learn LINQ union method in c#, vb.net with example and how to use LINQ union method to combine and get resultant collection with unique elements in c#, vb.net with example.

LINQ Union Method

In LINQ union method or operator is used to combine multiple collections into single collection and return resultant collection with unique elements.

 

Following is the pictorial representation of LINQ union method.

 

LINQ Union Method with Example

 

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

Syntax of LINQ union Method

Following is the syntax of using 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 above syntax we are combining two collections to get result as a single collection using union method.

Example of LINQ Union Method

Following is the example of using 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 above example we are combining two collections “count1”, “count2” using union method to get only unique elements from both the collections.

Output of LINQ Union Method Example

Following is the result of LINQ union method example.

 

UK

Australia

India

USA

Canada

China

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

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User