System.Linq.Enumerable.Union<TSource> Method

System.Linq

Returns the set union of two sequences.

public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)

This method supports a simple, declarative programming style that enables the creation of new sequences from existing ones. This method is implemented using deferred execution.

Parameters

first
An IEnumerable<TSource> whose elements are in the source sequence.
second
An IEnumerable<TSource> whose elements are in the second sequence.

Returns

IEnumerable<TSource>
An IEnumerable<TSource> that contains the elements from both sequences, with duplicates removed.

Remarks

The Union method returns the set union of two sequences. A set union is the set of all elements that are in either sequence, or in both. Duplicate elements are removed.

The order of elements in the result is not guaranteed. If the type of elements in the sequences implements the IEqualityComparer<TSource> interface, that implementation will be used to determine equality; otherwise, the default equality comparer for TSource will be used.

Examples

Example 1: Basic Union

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<int> numbers1 = new List<int> { 1, 2, 3 }; List<int> numbers2 = new List<int> { 3, 4, 5 }; IEnumerable<int> unionNumbers = numbers1.Union(numbers2); Console.WriteLine("Union of numbers:"); foreach (int number in unionNumbers) { Console.Write(number ); } // Output: Union of numbers: 1 2 3 4 5 } }

Example 2: Union with Strings

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { string[] fruits1 = new string[] { "Apple", "Banana" }; string[] fruits2 = new string[] { "Banana", "Orange" }; IEnumerable<string> unionFruits = fruits1.Union(fruits2); Console.WriteLine("Union of fruits:"); foreach (string fruit in unionFruits) { Console.WriteLine(fruit); } // Output: // Union of fruits: // Apple // Banana // Orange } }