C#에서 HashSet에 지정된 요소가 포함되어 있는지 확인하려면 Contains() 메서드를 사용합니다. 이 메서드는 해당 요소가 집합 안에 존재하면 true, 존재하지 않으면 false를 반환하므로, 조건문과 함께 활용하면 매우 편리합니다.
예제 1: 정수형 HashSet에서 요소 포함 여부 확인
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
HashSet<int> set1 = new HashSet<int>();
set1.Add(25);
set1.Add(50);
set1.Add(75);
set1.Add(100);
set1.Add(125);
set1.Add(150);
Console.WriteLine("HashSet1의 요소");
foreach(int val in set1){
Console.WriteLine(val);
}
HashSet<int> set2 = new HashSet<int>();
set2.Add(30);
set2.Add(60);
set2.Add(100);
set2.Add(150);
set2.Add(200);
set2.Add(250);
Console.WriteLine("HashSet2의 요소");
foreach(int val in set2){
Console.WriteLine(val);
}
Console.WriteLine("두 집합은 공통 요소를 가지고 있는가? " + set1.Overlaps(set2));
Console.WriteLine("HashSet1에 60이 있는가? " + set1.Contains(60));
Console.WriteLine("HashSet2에 60이 있는가? " + set2.Contains(60));
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
HashSet1의 요소 25 50 75 100 125 150 HashSet2의 요소 30 60 100 150 200 250 두 집합은 공통 요소를 가지고 있는가? True HashSet1에 60이 있는가? False HashSet2에 60이 있는가? True
위 예제에서 Contains(60)은 set1에는 해당 값이 없어 False를 반환하고, set2에는 값이 존재하므로 True를 반환합니다. 또한 Overlaps() 메서드를 사용하면 두 집합이 공통 요소를 하나라도 공유하는지 여부도 함께 확인할 수 있습니다.
예제 2: 문자열 HashSet에서 요소 포함 여부 확인
이번에는 문자열을 저장하는 HashSet에서 특정 요소의 존재 여부를 if 문과 함께 확인해 보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("Tim");
hashSet.Add("Jack");
hashSet.Add("Matt");
hashSet.Add("Steve");
hashSet.Add("David");
hashSet.Add("Kane");
hashSet.Add("Gary");
Console.WriteLine("HashSet의 요소");
foreach(string val in hashSet){
Console.WriteLine(val);
}
if (hashSet.Contains("Matt"))
Console.WriteLine("Matt 요소는 HashSet에 존재합니다.");
else
Console.WriteLine("Matt 요소는 HashSet에 존재하지 않습니다.");
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
HashSet의 요소 Tim Jack Matt Steve David Kane Gary Matt 요소는 HashSet에 존재합니다.
정리
Contains() 메서드는 HashSet 내부에서 해시 기반 탐색을 수행하기 때문에 일반적인 컬렉션보다 훨씬 빠른 속도로 요소 존재 여부를 판별할 수 있습니다. 따라서 대량의 데이터에서 특정 값의 존재 여부를 자주 확인해야 하는 경우 HashSet과 Contains 메서드를 조합해 사용하는 것이 효율적입니다.