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

C#에서 두 개의 딕셔너리 키를 하나로 결합하는 방법

C# 프로그래밍을 하다 보면 두 개의 Dictionary(딕셔너리)에 담긴 키(key)들을 하나로 합쳐야 하는 경우가 종종 발생합니다. 이럴 때 HashSetUnionWith() 메서드를 활용하면 매우 간단하게 해결할 수 있습니다. 이 글에서는 실제 예제 코드와 함께 그 과정을 단계별로 살펴보겠습니다.

1. 결합할 딕셔너리 준비하기

먼저 합치고자 하는 두 개의 딕셔너리를 생성하고 각각 요소를 추가합니다.

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

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

2. HashSet의 UnionWith() 메서드로 키 결합하기

첫 번째 딕셔너리의 키들(dict1.Keys)로 HashSet을 초기화한 뒤, UnionWith() 메서드를 호출하여 두 번째 딕셔너리의 키들을 합칩니다.

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

UnionWith()는 집합 연산 메서드로, 현재 HashSet에 지정된 컬렉션의 모든 요소를 추가하되 중복된 값은 자동으로 제거해 줍니다. 따라서 두 딕셔너리에 동일한 키가 존재하더라도 결과에는 한 번만 포함됩니다.

전체 예제 코드

using System;
using System.Collections.Generic;

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

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

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

        Console.WriteLine("Union of Dictionary...");
        foreach(string val in hSet) {
            Console.WriteLine(val);
        }
    }
}

실행 결과

Union of Dictionary...
one
Two
Three
Four

참고: LINQ를 활용한 대안

HashSet 대신 LINQ를 선호한다면 Concat()Distinct()를 조합하거나 Union() 메서드를 사용해 같은 결과를 얻을 수도 있습니다.

var combinedKeys = dict1.Keys.Union(dict2.Keys).ToList();

다만 단순히 키 집합을 합치는 작업이라면 HashSet의 UnionWith()가 성능 면에서 더 효율적이며 코드 의도도 명확하게 드러납니다.