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

C#에서 두 개의 Dictionary(딕셔너리) 병합하기 – HashSet과 UnionWith() 활용법

C# 프로그래밍을 하다 보면 두 개의 Dictionary를 하나로 합쳐야 하는 상황이 자주 발생합니다. 이번 글에서는 HashSet 클래스와 UnionWith() 메서드를 활용해 두 딕셔너리의 키(Key)를 손쉽게 병합하는 방법을 단계별로 살펴보겠습니다.

두 개의 딕셔너리 선언하기

먼저 병합 대상이 될 두 개의 딕셔너리를 생성합니다. 첫 번째 딕셔너리에는 laptop(노트북)과 desktop(데스크톱), 두 번째 딕셔너리에는 desktop(데스크톱), tablet(태블릿), mobile(모바일) 항목이 담겨 있습니다. 여기서 주목할 점은 두 딕셔너리 모두 'desktop'이라는 공통 키를 가지고 있다는 것입니다.

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

Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("desktop", 3);
dict2.Add("tablet", 4);
dict2.Add("mobile", 5);

HashSet과 UnionWith() 메서드로 병합하기

병합 작업은 HashSet<string> 객체를 첫 번째 딕셔너리의 키들로 초기화한 뒤, UnionWith() 메서드를 호출해 두 번째 딕셔너리의 키까지 합치는 방식으로 진행됩니다. UnionWith()는 집합 연산 메서드로, 중복된 키는 자동으로 제거되기 때문에 각 키가 결과에 한 번씩만 포함됩니다.

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

전체 예제 코드

지금까지 설명한 내용을 하나로 정리한 전체 코드는 다음과 같습니다.

using System;
using System.Collections.Generic;

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

        Dictionary<string, int> dict2 = new Dictionary<string, int>();
        dict2.Add("desktop", 3);
        dict2.Add("tablet", 4);
        dict2.Add("mobile", 5);

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

        Console.WriteLine("Merged Dictionary...");

        foreach(string val in hSet) {
            Console.WriteLine(val);
        }
    }
}

실행 결과

프로그램을 실행하면 두 딕셔너리에서 중복 없이 병합된 고유한 키들이 출력됩니다. 'desktop'은 양쪽 딕셔너리에 모두 존재하지만 결과에는 한 번만 표시되는 것을 확인할 수 있습니다.

Merged Dictionary...
laptop
desktop
tablet
mobile

참고: 위 방식은 딕셔너리의 키(Key)만 병합하며 값(Value)은 유지되지 않습니다. 키와 값을 함께 보존하면서 병합하고 싶다면 LINQ의 Concat(), GroupBy() 또는 TryAdd() 메서드를 활용하는 것이 좋습니다.