Home
C#
Union Example
This page was last reviewed on Oct 9, 2024.
Dot Net Perls
Union. This C# method computes mathematical unions. This extension method, from System.Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found.
Extension
Union removes duplicates. So this method can be thought of as two actions: it combines the two collections and then uses Distinct() on them, removing duplicate elements.
Distinct
First, Union() is found in System.Linq. So you will want to include the appropriate using-directive. The Union method will work with 2 collections of the same type of elements.
Tip Union works on Lists and arrays. We use integer arrays, but they could be string arrays or integer List types.
List
Array
Thus The Union of 1, 2, 3 and 2, 3, 4 is 1, 2, 3, 4. Elements are here compared for equality by Union using the default comparison logic.
using System; using System.Linq; // 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); }
1 2 3 4
Example 2. Union does not sort. The first example makes the result appear sorted, but this is due to already-sorted arrays. Here, I union two unsorted char arrays. The result is not sorted.
char Array
var
string.Join
using System; using System.Linq; char[] values1 = { 'a', 'z', 'c' }; char[] values2 = { 'c', 's' }; // Take union. var result = values1.Union(values2); Console.WriteLine(string.Join(",", result));
a,z,c,s
With Union, we combine collections. An imperative approach would involve a hash table or Dictionary. But the Union method can resolve duplicates automatically.
Please note the Intersect method. This returns only the shared elements in both collections it is called upon. It is similar to Union but with this important difference.
Intersect
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 9, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.