Linq Intersect Method

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

 

Following is the pictorial representation of the LINQ intersect method.

 

LINQ Intersect Method with Example

 

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

Syntax of LINQ Intersect Method

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

Example of LINQ Intersect Method

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

Result of LINQ Intersect Method Example

Following is the result of the 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.