C#에서 HashSet과 지정된 컬렉션이 서로 같은 요소들을 포함하고 있는지 확인하려면 SetEquals() 메서드를 사용하면 됩니다. 이 메서드는 두 집합이 동일한 요소를 가지고 있으면 True를, 그렇지 않으면 False를 반환합니다.
예제 1: 다른 요소를 가진 경우
아래 예제에서는 두 개의 문자열 HashSet을 생성합니다. set1에는 일곱 개의 요소가, set2에는 네 개의 요소가 들어 있으므로 두 집합은 같지 않습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
HashSet<string> set1 = new HashSet<string>();
set1.Add("One");
set1.Add("Two");
set1.Add("Three");
set1.Add("Four");
set1.Add("Five");
set1.Add("Six");
set1.Add("Seven");
HashSet<string> set2 = new HashSet<string>();
set2.Add("One");
set2.Add("Two");
set2.Add("Three");
set2.Add("Four");
Console.WriteLine("두 집합은 같은 요소를 포함하고 있습니까? = " + set1.SetEquals(set2));
}
}출력 결과
두 집합은 같은 요소를 포함하고 있습니까? = False
예제 2: 동일한 요소를 가진 경우
이번에는 정수형 HashSet 두 개에 완전히 같은 요소들을 추가한 후 비교해 보겠습니다. 두 집합이 동일한 요소를 모두 포함하고 있으므로 SetEquals()는 True를 반환합니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
HashSet<int> set1 = new HashSet<int>();
set1.Add(100);
set1.Add(200);
set1.Add(300);
set1.Add(400);
set1.Add(500);
set1.Add(600);
HashSet<int> set2 = new HashSet<int>();
set2.Add(100);
set2.Add(200);
set2.Add(300);
set2.Add(400);
set2.Add(500);
set2.Add(600);
Console.WriteLine("두 집합은 같은 요소를 포함하고 있습니까? = " + set1.SetEquals(set2));
}
}출력 결과
두 집합은 같은 요소를 포함하고 있습니까? = True
정리
SetEquals() 메서드는 HashSet이 지정된 컬렉션과 동일한 요소 집합을 가지고 있는지 판별할 때 유용합니다. 요소의 개수나 순서와 무관하게 포함된 요소 자체만 비교하며, 중복 없는 집합 특성 덕분에 비교 연산이 효율적으로 수행됩니다.