LINQ UnionBy

Summary: in this tutorial, you will learn how to use the LINQ UnionBy() method to create a union of two sequences based on a key selector function.

Introduction to the LINQ UnionBy() method

The UnionBy() method takes two sequences and returns a set union of them based on a specified key selector function.

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

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

In this syntax:

  • TSource represents the type of elements of the input sequences while TKey is the type of key that is used to identify elements.
  • first and second are input sequences with the type IEnumerable<T>.
  • keySelector is a function to extract the key for each element.

The UnionBy() method returns a sequence IEnumerable<T> that contains unique elements from the first and second sequences.

Typically, you use the UnionBy() method to create a set union of sequences of custom types. For the primitive types, you should use the Union() method.

LINQ UnionBy() method example

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)

To create a union of two lists of Person objects, you have to define a custom equality comparer and pass it to the Union() method.

However, if you use the UnionBy() method, you don’t need a custom equality comparer since you can use the key selector function to specify which property of the Person object is used for comparison.

For example:

using static System.Console;

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

var team2 = new List<Person>
{
    new Person() { SSN="123456781", Name="John Doe" },
    new Person() { SSN="123456784", Name="Sarah Davis" },
};

var team = team1.UnionBy(team2, p => p.SSN);

foreach (var person in team)
{
    WriteLine(person);
}Code language: C# (cs)

Output:

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

In this example, the key selector function:

p => p.SSNCode language: C# (cs)

specifies that UnionBy() should use the SSN of the Person object for comparing the Person objects.

Summary

  • Use the LINQ UnionBy() method to create a union of two sequences based on a key selector function.
Was this tutorial helpful ?