C#에서 Hashtable에 저장된 요소들을 순회하려면 GetEnumerator() 메서드를 사용하여 열거자(enumerator)를 가져올 수 있습니다. 이 메서드는 IDictionaryEnumerator 타입의 열거자를 반환하며, MoveNext() 메서드와 함께 사용하면 키(Key)와 값(Value) 쌍을 하나씩 차례대로 읽어올 수 있습니다.
Hashtable은 해시 기반 컬렉션이므로 요소의 저장 순서가 보장되지 않으며, 출력 결과에서도 키가 입력한 순서와 다르게 나타날 수 있다는 점을 참고하세요.
예제 1
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable(10);
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 the Hashtable having fixed size? = "+hash.IsFixedSize);
Console.WriteLine("Count of entries in Hashtable = "+ hash.Count);
Console.WriteLine("\nEnumerator to iterate through the Hashtable...");
IDictionaryEnumerator demoEnum = hash.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
hash.Clear();
}
}출력 결과
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 the Hashtable having fixed size? = False Count of entries in Hashtable = 10 Enumerator to iterate through the Hashtable... Key = 10, Value = J Key = 1, Value = A Key = 2, Value = B Key = 3, Value = C Key = 4, Value = D Key = 5, Value = E Key = 6, Value = F Key = 7, Value = G Key = 8, Value = H Key = 9, Value = I
위 예제에서 먼저 foreach 문과 DictionaryEntry를 사용해 Hashtable의 모든 키-값 쌍을 출력했습니다. 이후 IsFixedSize 속성으로 크기 고정 여부를 확인하고, Count 속성으로 전체 항목 수를 확인했습니다. 마지막으로 GetEnumerator()로 얻은 열거자를 통해 MoveNext()가 true를 반환하는 동안 각 항목의 Key와 Value를 출력합니다.
예제 2
이번에는 문자열 키를 사용한 또 다른 예제를 살펴보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable(10);
hash.Add("One", "A");
hash.Add("Two", "B");
hash.Add("Three", "C");
hash.Add("Four", "D");
hash.Add("Five","E");
hash.Add("Six", "F");
Console.WriteLine("Hashtable Key and Value pairs...");
Console.WriteLine("\nEnumerator to iterate through the Hashtable...");
IDictionaryEnumerator demoEnum = hash.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
hash.Clear();
}
}출력 결과
Hashtable Key and Value pairs... Enumerator to iterate through the Hashtable... Key = One, Value = A Key = Five, Value = E Key = Three, Value = C Key = Two, Value = B Key = Four, Value = D Key = Six, Value = F
출력 결과를 보면 키가 추가한 순서(One, Two, Three...)가 아닌 해시 코드에 따른 순서로 출력되는 것을 확인할 수 있습니다. 이는 Hashtable이 내부적으로 해시 함수를 기반으로 요소를 배치하기 때문입니다.
핵심 정리
- GetEnumerator(): Hashtable을 순회할 수 있는 IDictionaryEnumerator를 반환합니다.
- MoveNext(): 다음 요소로 이동하며, 더 이상 요소가 없으면 false를 반환합니다.
- Key / Value 속성: 현재 위치한 항목의 키와 값을 각각 제공합니다.
- Clear(): Hashtable의 모든 요소를 제거합니다.