C# Union Extension Method

LINQ (language integrated query)

Union computes mathematical unions. This extension method acts upon two collections. It returns a new collection that contains the elements that are found. It removes duplicates.

This C# example program uses the Union extension method from System.Linq.

Example

Note

First, the Union method is accessed through the System.Linq namespace, so you will want to include that using directive at the top of your program text. The Union method will work with two collections of the same type of elements; this includes List types, and array types. In this example, we use integer arrays, but they could be string arrays or integer List types. The Union of 1, 2, 3 and 2, 3, 4 is 1, 2, 3, 4.

Program that invokes Union method [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Create two example arrays.
	int[] array1 = { 1, 2, 3 };
	int[] array2 = { 2, 3, 4 };
	// Union the two arrays.
	var result = array1.Union(array2);
	// Enumerate the union.
	foreach (int value in result)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

1
2
3
4

Summary

The C# programming language

We looked at the Union extension method from the System.Linq namespace in the C# programming language. While the imperative approach to computing unions would involve a hashtable or Dictionary in many contexts, the Union method can resolve duplicates automatically, leading to higher levels of code simplicity. An interesting complement to the Union method is the Intersect method, which returns only the shared elements in both collections it is called upon.

Intersect LINQ Examples
.NET