Returns the set union of two sequences.
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.
IEnumerable<TSource>
whose elements are in the source sequence.IEnumerable<TSource>
whose elements are in the second sequence.IEnumerable<TSource>
IEnumerable<TSource>
that contains the elements from both sequences, with duplicates removed.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.
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
}
}
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
}
}