Enumerable.Union 메서드

정의

두 시퀀스의 집합 결합을 생성합니다.

오버로드

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

기본 같음 비교자를 사용하여 두 시퀀스의 집합 합합을 생성합니다.

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

지정된 IEqualityComparer<T>사용하여 두 시퀀스의 집합 합합을 생성합니다.

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

Source:
Union.cs
Source:
Union.cs
Source:
Union.cs

기본 같음 비교자를 사용하여 두 시퀀스의 집합 합합을 생성합니다.

C#
public static System.Collections.Generic.IEnumerable<TSource> Union<TSource> (this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second);

형식 매개 변수

TSource

입력 시퀀스의 요소 형식입니다.

매개 변수

first
IEnumerable<TSource>

고유 요소가 공용 구조체의 첫 번째 집합을 형성하는 IEnumerable<T>.

second
IEnumerable<TSource>

고유 요소가 공용 구조체의 두 번째 집합을 형성하는 IEnumerable<T>.

반환

IEnumerable<TSource>

중복을 제외한 두 입력 시퀀스의 요소가 포함된 IEnumerable<T>.

예외

first 또는 secondnull.

예제

다음 코드 예제에서는 Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) 사용하여 두 개의 정수 시퀀스의 합합을 가져오는 방법을 보여 줍니다.

C#
int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };

IEnumerable<int> union = ints1.Union(ints2);

foreach (int num in union)
{
    Console.Write("{0} ", num);
}

/*
 This code produces the following output:

 5 3 9 7 8 6 4 1 0
*/

일부 사용자 지정 데이터 형식의 개체 시퀀스를 비교하려면 도우미 클래스에서 IEquatable<T> 제네릭 인터페이스를 구현해야 합니다. 다음 코드 예제에서는 사용자 지정 데이터 형식에서 이 인터페이스를 구현하고 GetHashCodeEquals 메서드를 재정의하는 방법을 보여 줍니다.

C#
public class ProductA : IEquatable<ProductA>
{
    public string Name { get; set; }
    public int Code { get; set; }

    public bool Equals(ProductA other)
    {
        if (other is null)
            return false;

        return this.Name == other.Name && this.Code == other.Code;
    }

    public override bool Equals(object obj) => Equals(obj as ProductA);
    public override int GetHashCode() => (Name, Code).GetHashCode();
}

이 인터페이스를 구현한 후 다음 예제와 같이 Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) 메서드에서 ProductA 개체 시퀀스를 사용할 수 있습니다.

C#
ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 },
                       new ProductA { Name = "orange", Code = 4 } };

ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 },
                       new ProductA { Name = "lemon", Code = 12 } };
C#
//Get the products from the both arrays
//excluding duplicates.

IEnumerable<ProductA> union =
  store1.Union(store2);

foreach (var product in union)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:

    apple 9
    orange 4
    lemon 12
*/

설명

이 메서드는 지연된 실행을 사용하여 구현됩니다. 즉시 반환 값은 작업을 수행하는 데 필요한 모든 정보를 저장하는 개체입니다. 이 메서드가 나타내는 쿼리는 개체가 GetEnumerator 메서드를 직접 호출하거나 C#의 foreach 사용하거나 Visual Basic에서 For Each 열거될 때까지 실행되지 않습니다.

이 메서드는 반환 집합에서 중복 항목을 제외합니다. 이는 중복을 포함하여 입력 시퀀스의 모든 요소를 반환하는 Concat 메서드와는 다른 동작입니다.

Default기본 같음 비교자는 IEqualityComparer<T> 제네릭 인터페이스를 구현하는 형식의 값을 비교하는 데 사용됩니다. 사용자 지정 데이터 형식을 비교하려면 이 인터페이스를 구현하고 형식에 대한 고유한 GetHashCodeEquals 메서드를 제공해야 합니다.

이 메서드에서 반환된 개체가 열거되면 Union 해당 순서로 firstsecond 열거하고 아직 생성되지 않은 각 요소를 생성합니다.

적용 대상

.NET 9 및 기타 버전
제품 버전
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

Source:
Union.cs
Source:
Union.cs
Source:
Union.cs

지정된 IEqualityComparer<T>사용하여 두 시퀀스의 집합 합합을 생성합니다.

C#
public static System.Collections.Generic.IEnumerable<TSource> Union<TSource> (this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, System.Collections.Generic.IEqualityComparer<TSource> comparer);
C#
public static System.Collections.Generic.IEnumerable<TSource> Union<TSource> (this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second, System.Collections.Generic.IEqualityComparer<TSource>? comparer);

형식 매개 변수

TSource

입력 시퀀스의 요소 형식입니다.

매개 변수

first
IEnumerable<TSource>

고유 요소가 공용 구조체의 첫 번째 집합을 형성하는 IEnumerable<T>.

second
IEnumerable<TSource>

고유 요소가 공용 구조체의 두 번째 집합을 형성하는 IEnumerable<T>.

comparer
IEqualityComparer<TSource>

값을 비교할 IEqualityComparer<T>.

반환

IEnumerable<TSource>

중복을 제외한 두 입력 시퀀스의 요소가 포함된 IEnumerable<T>.

예외

first 또는 secondnull.

예제

다음 예제에서는 Union 메서드에서 사용할 수 있는 같음 비교자를 구현하는 방법을 보여 있습니다.

C#
public class Product
{
    public string Name { get; set; }
    public int Code { get; set; }
}

// Custom comparer for the Product class
class ProductComparer : IEqualityComparer<Product>
{
    // Products are equal if their names and product numbers are equal.
    public bool Equals(Product x, Product y)
    {

        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the products' properties are equal.
        return x.Code == y.Code && x.Name == y.Name;
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.

    public int GetHashCode(Product product)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(product, null)) return 0;

        //Get hash code for the Name field if it is not null.
        int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

        //Get hash code for the Code field.
        int hashProductCode = product.Code.GetHashCode();

        //Calculate the hash code for the product.
        return hashProductName ^ hashProductCode;
    }
}

이 비교자를 구현한 후 다음 예제와 같이 Union 메서드에서 Product 개체의 시퀀스를 사용할 수 있습니다.

C#
Product[] store10 = { new Product { Name = "apple", Code = 9 },
                       new Product { Name = "orange", Code = 4 } };

Product[] store20 = { new Product { Name = "apple", Code = 9 },
                       new Product { Name = "lemon", Code = 12 } };

//Get the products from the both arrays
//excluding duplicates.

IEnumerable<Product> union =
  store10.Union(store20, new ProductComparer());

foreach (Product product in union)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:

    apple 9
    orange 4
    lemon 12
*/

설명

이 메서드는 지연된 실행을 사용하여 구현됩니다. 즉시 반환 값은 작업을 수행하는 데 필요한 모든 정보를 저장하는 개체입니다. 이 메서드가 나타내는 쿼리는 개체가 GetEnumerator 메서드를 직접 호출하거나 C#의 foreach 사용하거나 Visual Basic에서 For Each 열거될 때까지 실행되지 않습니다.

comparer null경우 기본 같음 비교자인 Default값을 비교하는 데 사용됩니다.

이 메서드에서 반환된 개체가 열거되면 Union 해당 순서로 firstsecond 열거하고 아직 생성되지 않은 각 요소를 생성합니다.

Concat 메서드는 중복을 포함하여 입력 시퀀스의 모든 요소를 반환하는 반면 Union 고유 값만 반환하므로 Concat 메서드는 Union 메서드와 다릅니다.

추가 정보

적용 대상

.NET 9 및 기타 버전
제품 버전
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0