C#에서 Hashtable은 키(Key)와 값(Value)을 쌍으로 저장하는 컬렉션입니다. 저장된 여러 요소 중에서 특정 값(Value)이 존재하는지 확인하고 싶다면 ContainsValue() 메서드를 사용하면 간단하게 처리할 수 있습니다.
1. Hashtable에 요소 추가하기
먼저 Hashtable 컬렉션을 생성하고 Add() 메서드로 요소를 추가합니다.
Hashtable h = new Hashtable(); h.Add(1, "Jack"); h.Add(2, "Henry"); h.Add(3, "Ben"); h.Add(4, "Chris");
2. ContainsValue() 메서드로 값 찾기
이제 특정 값이 Hashtable에 있는지 확인해야 한다면 ContainsValue() 메서드를 호출합니다. 이 메서드는 해당 값이 존재하면 true, 존재하지 않으면 false를 반환합니다.
예를 들어, "Chris"라는 값이 존재하는지 확인하는 코드는 다음과 같습니다.
h.ContainsValue("Chris");
전체 예제 코드
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable h = new Hashtable();
h.Add(1, "Jack");
h.Add(2, "Henry");
h.Add(3, "Ben");
h.Add(4, "Chris");
Console.WriteLine("Keys and Values list:");
foreach (var key in h.Keys) {
Console.WriteLine("Key = {0}, Value = {1}", key, h[key]);
}
Console.WriteLine("Value Chris exists? " + h.ContainsValue("Chris"));
Console.WriteLine("Value Tom exists? " + h.ContainsValue("Tom"));
}
}
실행 결과
Keys and Values list: Key = 4, Value = Chris Key = 3, Value = Ben Key = 2, Value = Henry Key = 1, Value = Jack Value Chris exists? True Value Tom exists? False
참고: 키(Key) 검색은 ContainsKey() 활용
값이 아닌 키(Key)의 존재 여부를 확인하려면 ContainsKey() 메서드를 사용하는 것이 좋습니다. Hashtable은 내부적으로 해시 기반으로 키를 조회하기 때문에 ContainsKey()가 값 전체를 순회하는 ContainsValue()보다 훨씬 빠르게 동작합니다.
정리하면, ContainsValue()는 값 기준 검색에 적합하며, 성능이 중요한 키 검색에는 ContainsKey()를 사용하는 것이 바람직합니다.