LINQ Union

Summary: in this tutorial, you will learn how to use the LINQ Union() method to produce the set union of two sequences.

Introduction to the LINQ Union() method

The Union() method returns the union of two sequences. Here’s the syntax of the Union() method:

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

In this syntax:

  • TSource represents the type of elements in the first and second sequences.
  • first is an IEnumerable<T> whose distinct elements create the first set for the union.
  • second is also an IEnumerable<T> whose distinct elements create the second set of the union.

The Union() returns an IEnumerable<T> that contains the unique elements that appear in the first and second sequences.

The Union() method uses the default equality comparer. It means that the method will compare elements by value if they are primitive types or by references if they are objects.

To create a union of custom type, you can define a class that implements the IEqualityComparer<T> interface and pass the custom equality comparer object to another overload of the Union() method:

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

LINQ Union() method examples

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

1) Using LINQ Union() method with sequences of numbers

The following example uses the Union() method to create a union of sequences of integers. Because the integer is a primitive type, the Union() method compares them by values:

using static System.Console;

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

var numbers = numbers1.Union(numbers2);

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

Output:

1
2
3
4
5Code language: C# (cs)

The output shows that the result of the Union() method contains unique numbers that appear in the input sequences.

2) Using LINQ Union() method with sequences of strings

The following example uses the Union() method to create a union of strings:

using static System.Console;

var names1 = new List<string>() { "John", "Jane", "Joe" };
var names2 = new List<string>() { "Jane", "Alice", "Bob" };

var names = names1.Union(names2);

foreach (var name in names)
{
    WriteLine(name);
}Code language: C# (cs)

Output:

John
Jane
Joe
Alice
BobCode language: C# (cs)

3) Using LINQ Union() method with sequences of objects

To create a union of a custom type, you can create a custom equality comparer or use a UnionBy() method instead.

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)

Two people are the same if they have the same SSN. To enforce this, you define a PersonComparer that compares Person objects by SSN:

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 example uses the Union() method with a PersonComparer to find the union of two sequences of Person objects:

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.Union(team2);

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)

Summary

  • Use LINQ Union() method to create a union of two sequences, which contain unique elements from both sequences.
Was this tutorial helpful ?