C# Lessons

Concat vs union #L3

Okay, so let’s assume that you have some two lists. And now, you would like to merge them into one.

The Concat method combines two collections into one. However, it doesn’t perform any other operations. It simply returns one collection containing elements from two collections.

The Union method not only combines the two collections into one, but also performs the Distinct operation – so it eliminates duplicates. It will compare the reference of the items in the collection. If the elements of your collection have different references – they will be considered differently.

Now, let’s take a look at some code sample:

        var firstCollectionOfNumbers = new[] { 1, 2 };         
        var secondCollectionOfNumbers = new[] { 2, 3 };

        IEnumerable concatOfTwoCollections = firstCollectionOfNumbers.Concat(secondCollectionOfNumbers); 

        IEnumerable unionOfTwoCollections = firstCollectionOfNumbers.Union(secondCollectionOfNumbers);

        Console.WriteLine("Concat:");
        foreach (int element in concatOfTwoCollections)
        {
            Console.Write($"{element} ");
        } 
 
        Console.WriteLine(); 

        Console.WriteLine("Union:");
        foreach (int element in unionOfTwoCollections)
        {
            Console.Write($"{element} ");
        }

You can see here that we have two collections – one with numbers 1, 2 and second with numbers 2, 3.
According to the definition – for the same two collections the output of Concat and Union operations will be:
Concat:
1 2 2 3
Union:
1 2 3

Leave a Reply