LINQ Intersect

Summary: in this tutorial, you will learn how to use the LINQ Intersect() method to find the common elements that exist in both input sequences.

Introduction to the LINQ Intersect() method

The LINQ Intersect() method allows you to find the common elements that exist in both input sequences.

Here’s the syntax of the Intersect() method:

IEnumerable<TSource> Intersect<TSource> (
   this IEnumerable<TSource> first, 
   IEnumerable<TSource> second
);Code language: C# (cs)

The Intersect() method accepts two input sequences as the parameters first and second. They both have the IEnumerable<T> type.

The Intersect() method returns a new sequence with the type IEnumerable<T> that contains the common elements of the first and second sequences.

The Intersect() method uses the default equality comparer to compare elements in the first and second sequences. It means that the Intersect() method compares the elements in the sequences by their references if they are objects, or by their values if they are primitive types.

If you want to override the default equality comparer, you can define a custom equality comparer by implementing the IEqualityComparer interface and passing the customer equality comparer object to the second overload of the Intersect() method as follows:

IEnumerable<TSource> Intersect<TSource> (
   this IEnumerable<TSource> first, 
   IEnumerable<TSource> second,
   IEqualityComparer<TSource>? comparer
);Code language: C# (cs)

LINQ Intersect() method examples

Let’s take some examples of using the LINQ Intersect() method.

1) Using the LINQ Intersect() method to find the common elements of two sequences of numbers

The following example uses the Intersect() method to find the numbers that exist in both lists of numbers:

using static System.Console;

var numbers1 = new List<int>() { 1, 2, 3, 4 };
var numbers2 = new List<int>() { 2, 3, 4, 5 };

var commonNumbers = numbers1.Intersect(numbers2);

foreach (var number in commonNumbers)
{
    WriteLine(number);
}Code language: C# (cs)

Output:

2
3
4

2) Using the LINQ Intersect() method to find the common elements of two sequences of strings

The following example uses the Intersect() method to find the common elements of two arrays of strings:

using static System.Console;

var mountains1 = new[] { "Everest", "Kilimanjaro", "Fuji", "Matterhorn" };
var mountains2 = new[] { "Kilimanjaro", "Fuji", "Matterhorn", "Denali" };

var mountains = mountains1.Intersect(mountains2);
foreach (var mountain in mountains)
{
    WriteLine(mountain);
}Code language: C# (cs)

Output:

Kilimanjaro
Fuji
Matterhorn

3) Using the LINQ Intersect() method to find the common elements of two sequences of objects

Suppose you have a Person class with two properties SSN and Name:

public class Person
{
    public required string SSN
    {
        get; set;
    }
    public required string Name
    {
        get; set;
    }

    public override string ToString() => $"{Name} <{SSN}>";
}Code language: C# (cs)

And you want to compare two Person objects by their SSN. In other words, two people are the same if they have the same SSN.

To do that you can define the PersonComparer that implements the IEqualityComparer interface as follows:

public class PersonComparer : IEqualityComparer<Person>
{
    public bool Equals(Person? x, Person? y)
    {
        // Check for null values
        if (x == null || y == null)
            return false;

        // Check if the two Person objects are the same reference
        if (ReferenceEquals(x, y))
            return true;

        // Compare the SSN of the two Person objects
        // to determine if they're the same
        return x.SSN == y.SSN;
    }

    public int GetHashCode(Person? obj)
    {
        if (obj == null || obj.SSN == null)
            return 0;

        // Use the SSN of the Person object
        // as the hash code
        return obj.SSN.GetHashCode();
    }
}Code language: C# (cs)

The following program uses the Intersect() method with the PersonComparer to find Person objects that appears on both list:

using static System.Console;

var employees1 = new List<Person>
{
    new Person() { SSN="123456781", Name="John Doe" },
    new Person() { SSN="123456782", Name="Jane Doe" },
    new Person() { SSN="123456783", Name="William Brown" },
    new Person() { SSN="123456784", Name="Sarah Davis" },
};

var employees2 = new List<Person>
{
    new Person() { SSN="123456781", Name="John Doe" },
    new Person() { SSN="123456782", Name="Jane Doe" },
    new Person() { SSN="123456784", Name="Sarah Davis" },
    new Person() { SSN="123456785", Name="Emily Johnson" },

};


var employees = employees1.Intersect(
    employees2, 
    new PersonComparer()
);

foreach (var employee in employees)
{
    WriteLine(employee);
}Code language: C# (cs)

Output:

John Doe <123456781>
Jane Doe <123456782>
Sarah Davis <123456784>Code language: C# (cs)

Summary

  • Use LINQ Intersect() method to return the elements that exist in both input sequences.
  • Use a custom equality comparer to override the default equality comparer.
Was this tutorial helpful ?