Linq Intersect Method

In LINQ, Intersect method or operator is used to return common elements from both the collections.

 

Following is the pictorial representation of LINQ intersect method.

 

LINQ Intersect Method with Example

 

The LINQ intersect method will combine both the collections into single collection and return only matching elements from the collections.

Syntax of LINQ Intersect Method

Following is the syntax of using intersect method to get matching elements from multiple collections.

 

C# Code

 

var result = count1.Intersect(count2);

VB.NET Code

 

Dim result = count1.Intersect(count2)

If you observe above syntax we are combining two collections to get result as a single collection using intersect method.

Example of LINQ Intersect Method

Following is the example of using LINQ intersect 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.Intersect(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.Intersect(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 Intersect method to get common elements from both the collections.

Output of LINQ Intersect Method Example

Following is the result of LINQ intersect method example.

 

UK

India

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