LINQ IntersectBy

Summary: in this tutorial, you will learn how to use the LINQ IntersectBy() method to find the set intersection of two sequences based on a specified key selector function.

Introduction to the LINQ IntersectBy() method

The Intersect() method returns a sequence that contains elements that appeared in both input sequences. It works great for numbers and strings.

When it comes to finding the intersection of two sequences of objects, you often need to implement IEqualityComparer interface and use it for comparing two objects.

.NET 6 addressed this issue by introducing the IntersectBy() method. The IntersectBy() method allows you to find the set intersection of two sequences based on a specified key selector function.

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

IEnumerable<TSource> IntersectBy<TSource,TKey> (
   this IEnumerable<TSource> first, 
   IEnumerable<TKey> second, 
   Func<TSource,TKey> keySelector
);Code language: C# (cs)

In this syntax:

  • TSource represents the type of elements in the input sequences, while the TKey represents the type of key used to identify elements.
  • first is an IEnumerable<TSource>.
  • second is an IEnumerable<TKey>.
  • keySelector is a function Func<TSource,TKey> that extracts a key from each element.

The IntersectBy() method returns a sequence containing elements that form the set intersection of the first and second sequences.

The IntersectBy() method returns distinct elements from both sequences in the order of their first appearance.

Note that the intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.

LINQ IntersectBy() method example

Let’s take some examples to understand the IntersectBy() method.

1) Using the LINQ IntersectBy() to find the intersection of two sequences of objects

Suppose we 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 need to find the intersection of two lists of Person objects by the SSN property.

In the Intersect() tutorial, you have to implement the IEqualityComparer that compare two Person object by the SSN key.

However, with the IntersectBy() method, you don’t need a custom equality comparer anymore.

For example, the following program uses the IntersectBy() method to find the intersection of two lists of Person objects:

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.IntersectBy(
    employees2.Select(e => e.SSN),
    e => e.SSN
);

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

Output:

John Doe <123456781>
Jane Doe <123456782>
Sarah Davis <123456784>Code language: plaintext (plaintext)

Let’s examine the following code:

var employees = employees1.IntersectBy(
    employees2.Select(e => e.SSN),
    e => e.SSN
);Code language: C# (cs)

In this code:

  • TSource is Employee and TKey is SSN.
  • employee1 is IEnumerable<Employee>
  • employees2.Select(e => e.SSN) returns an IEnumerable<string> that contains a sequence of the SSN.
  • The e => e.SSN is a key selector function that returns SSN as the key for comparison.

2) Using the LINQ IntersectBy() to find the intersection of two sequences of objects with different shapes

The following example uses the IntersectBy() method to find the intersection of a list of Employee records and a list of salaries:

using static System.Console;

public record Employee(string Name, decimal Salary);

public class Program
{
    public static void Main(string[] args)
    {
        var employees = new List<Employee>()
        {
            new Employee("John Doe", 120000),
            new Employee("John Doe", 100000),
            new Employee("Sarah Davis", 100000),
            new Employee("Emily Johnson", 150000)
        };

        var salaries = new decimal[] { 120000, 100000 };

        var results = employees.IntersectBy(salaries, e => e.Salary);
        foreach (var employee in results)
        {
            WriteLine(employee);
        }
    }
}Code language: C# (cs)

Output:

Employee { Name = John Doe, Salary = 120000 }
Employee { Name = Jane Doe, Salary = 100000 }Code language: plaintext (plaintext)

In this example, the IntersectBy() method compares the Salary of the Employee records with the elements in the salaries list. It returns an IEnumerable<Employee> that contains two records.

Even though Sarah Davis has a salary of 100000, the IntersectBy() method returns only the distinct values. In this case, Jane Doe appears first in the list, the IntersectBy() methods include only Jane Doe, not Sarah David.

Summary

  • Use LINQ IntersectBy()method to find the set intersection of two sequences based on a specified key selector function.
Was this tutorial helpful ?