Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 두 개 이상의 딕셔너리 합집합 구하기

C#에서 두 개 이상의 Dictionary(딕셔너리)의 합집합을 구하려면 HashSetUnionWith() 메서드를 활용하면 됩니다. 아래에서 단계별로 살펴보겠습니다.

1단계: 두 개의 딕셔너리 생성

먼저 합집합을 구할 두 개의 딕셔너리를 선언하고 요소를 추가합니다.

Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("water", 1);
dict1.Add("food", 2);

Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("clothing", 3);
dict2.Add("shelter", 4);

2단계: HashSet과 UnionWith()로 합집합 계산

첫 번째 딕셔너리의 키(Key)들로 HashSet을 초기화한 뒤, UnionWith() 메서드에 두 번째 딕셔너리의 키 컬렉션을 전달하면 두 딕셔너리의 모든 키가 중복 없이 하나의 집합으로 병합됩니다.

HashSet<string> hSet = new HashSet<string>(dict1.Keys);
hSet.UnionWith(dict2.Keys);

전체 예제 코드

다음은 위 과정을 모두 포함한 완성된 코드입니다.

using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        Dictionary<string, int> dict1 = new Dictionary<string, int>();
        dict1.Add("water", 1);
        dict1.Add("food", 2);

        Dictionary<string, int> dict2 = new Dictionary<string, int>();
        dict2.Add("clothing", 3);
        dict2.Add("shelter", 4);

        HashSet<string> hSet = new HashSet<string>(dict1.Keys);
        hSet.UnionWith(dict2.Keys);

        Console.WriteLine("딕셔너리의 합집합...");
        foreach(string val in hSet) {
            Console.WriteLine(val);
        }
    }
}

실행 결과

딕셔너리의 합집합...
water
food
clothing
shelter

핵심 정리

  • HashSet 초기화: 첫 번째 딕셔너리의 Keys 속성을 생성자에 전달하여 집합을 만듭니다.
  • UnionWith() 메서드: 다른 컬렉션의 요소들을 현재 HashSet에 병합하며, 자동으로 중복을 제거합니다.
  • 확장성: 세 개 이상의 딕셔너리도 UnionWith()를 반복 호출하여 같은 방식으로 합칠 수 있습니다.

이처럼 HashSet.UnionWith()를 사용하면 여러 딕셔너리의 키를 간단하고 효율적으로 하나의 집합으로 통합할 수 있습니다.