C#의 UnionWith 메서드를 사용하면 두 컬렉션에서 중복을 제거한 고유한 요소들, 즉 합집합(union)을 손쉽게 구할 수 있습니다. 이 메서드는 HashSet 클래스에서 제공되며, 다른 컬렉션의 요소들을 현재 집합에 병합하면서 자동으로 중복 요소를 걸러줍니다.
예제 데이터 준비
먼저 예제에 사용할 두 개의 Dictionary를 만들어 보겠습니다.
Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("pencil", 1);
dict1.Add("pen", 2);
Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("pen", 3);여기서 dict1에는 'pencil'과 'pen'이, dict2에는 'pen'이라는 키가 들어 있습니다. 두 컬렉션 모두 'pen' 키를 가지고 있으므로, 합집합 결과에는 'pen'이 한 번만 포함됩니다.
HashSet과 UnionWith로 합집합 구하기
Dictionary의 키 값들을 HashSet으로 변환한 뒤, UnionWith 메서드를 호출하여 두 번째 컬렉션의 키들을 병합합니다.
HashSet<string> hSet = new HashSet<string>(dict1.Keys); hSet.UnionWith(dict2.Keys);
HashSet은 내부적으로 해시 기반 구조를 사용하기 때문에 중복된 키는 자동으로 하나만 유지됩니다. 따라서 별도의 중복 검사 코드 없이 깔끔하게 합집합을 얻을 수 있습니다.
전체 코드
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("pencil", 1);
dict1.Add("pen", 2);
Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("pen", 3);
HashSet<string> hSet = new HashSet<string>(dict1.Keys);
hSet.UnionWith(dict2.Keys);
Console.WriteLine("Merged Dictionary...");
foreach(string val in hSet) {
Console.WriteLine(val);
}
}
}실행 결과
Merged Dictionary... pencil pen
정리
UnionWith 메서드는 두 컬렉션을 하나로 합치면서 중복을 제거해야 할 때 매우 유용합니다. 특히 Dictionary의 키 목록을 병합하는 경우, HashSet 생성자에 첫 번째 컬렉션의 Keys를 전달하고 UnionWith로 두 번째 컬렉션의 Keys를 추가하는 패턴이 가장 간결하고 효율적인 방법입니다. 참고로 C#에는 이 외에도 IntersectWith(교집합), ExceptWith(차집합), SymmetricExceptWith(대칭 차집합) 같은 집합 연산 메서드들이 함께 제공되므로, 상황에 맞게 활용하면 됩니다.