Linq Intersect Method

  Total Views : 161
  Comments : 0
 
  Keywords : Linq intersect operator with example in c# / vb.net, How to use linq intersect operator in c# / vb.net to get common elements from sequences with example, Linq enumerable.intersect method

Here we will learn LINQ Intersect method in c# / vb.net with example and how to use LINQ intersect method to get common elements from both the collections in c#, vb.net with example.

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.

 
 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User