
You want to quickly acquire the intersection of two collections in the C# language. In set theory, an intersection is the subset of each collection that is found in both collections. While you could use a Dictionary or nested loops to compute this, the Intersect method is more elegant.

This example program invokes the Intersect method in the System.Linq namespace. Please note how the two using directives at the top of the program specify where the types are located. We use the array initialized syntax to create the arrays. Each array has three numbers in it; both arrays have the numbers 2 and 3, and one other number. The results show that the Intersect method returns these exact numbers: 2 and 3.
This C# program shows the Intersect method from System.Linq.
Program that uses Intersect extension method [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call Intersect extension method.
var intersect = array1.Intersect(array2);
// Write intersection to screen.
foreach (int value in intersect)
{
Console.WriteLine(value);
}
}
}
Output
2
3
We examined the Intersect method that is found in the namespace System.Linq in the C# programming language. We saw how you can compute the intersecting part of two integer arrays using a declarative syntax, rather than an imperative loop construct. While a declarative syntax is more concise, an imperative style could improve the efficiency of this particular operation.
LINQ Examples