C#에서 Hashtable에 특정 값이 포함되어 있는지 확인하려면 ContainsValue() 메서드를 사용합니다. 이 메서드는 지정한 값이 Hashtable 내에 존재하면 true, 존재하지 않으면 false를 반환합니다.
예제 1
다음은 Hashtable에 특정 값이 있는지 확인하는 전체 코드입니다.
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable();
hash.Add("1", "A");
hash.Add("2", "B");
hash.Add("3", "C");
hash.Add("4", "D");
hash.Add("5", "E");
hash.Add("6", "F");
hash.Add("7", "G");
hash.Add("8", "H");
hash.Add("9", "I");
hash.Add("10", "J");
Console.WriteLine("Hashtable Key and Value pairs...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Is Hashtable having fixed size? = "+hash.IsFixedSize);
Console.WriteLine("If Hashtable read-only? = "+hash.IsReadOnly);
Console.WriteLine("The Hashtable consists of the value? = "+hash.ContainsValue("H"));
}
}실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Hashtable Key and Value pairs... 10 and J 1 and A 2 and B 3 and C 4 and D 5 and E 6 and F 7 and G 8 and H 9 and I Is Hashtable having fixed size? = False If Hashtable read-only? = False The Hashtable consists of the value? = True
예제 2
이번에는 키 확인 메서드인 ContainsKey()와 함께 ContainsValue()를 동시에 사용해 보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable();
hash.Add("One", "Katie");
hash.Add("Two", "John");
hash.Add("Three", "Barry");
hash.Add("Four", "Mark");
hash.Add("Five", "Harry");
hash.Add("Six", "Nathan");
hash.Add("Seven", "Tom");
hash.Add("Eight", "Andy");
hash.Add("Nine", "Illeana");
hash.Add("Ten", "Tim");
Console.WriteLine("Hashtable Key and Value pairs...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Is Hashtable having fixed size? = "+hash.IsFixedSize);
Console.WriteLine("If Hashtable read-only? = "+hash.IsReadOnly);
Console.WriteLine("The Hashtable consists of the key? = "+hash.ContainsKey("Seven"));
Console.WriteLine("The Hashtable consists of the value? = "+hash.ContainsValue("Illeana"));
}
}실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Hashtable Key and Value pairs... One and Katie Ten and Tim Five and Harry Three and Barry Seven and Tom Two and John Four and Mark Eight and Andy Nine and Illeana Six and Nathan Is Hashtable having fixed size? = False If Hashtable read-only? = False The Hashtable consists of the key? = True The Hashtable consists of the value? = True
핵심 정리
ContainsValue(Object value): Hashtable에 해당 값(Value)이 존재하는지 여부를 반환합니다.ContainsKey(Object key): Hashtable에 해당 키(Key)가 존재하는지 여부를 반환합니다.IsFixedSize: Hashtable의 크기가 고정되어 있는지 확인합니다.IsReadOnly: Hashtable이 읽기 전용인지 확인합니다.
참고로 Hashtable은 해시 기반 컬렉션이므로 요소를 추가한 순서대로 저장되지 않으며, 출력 순서는 실행 시마다 달라질 수 있습니다. 또한 ContainsValue()는 모든 항목을 순회하며 값을 비교하므로 O(n)의 시간 복잡도를 가지는 반면, ContainsKey()는 해시 조회를 통해 평균적으로 O(1)에 처리된다는 점도 기억해 두면 좋습니다.