C#에서 Hashtable에 새로운 요소를 추가할 때는 Add() 메서드를 사용합니다. 이 메서드는 키(Key)와 값(Value)을 인자로 받아 해시테이블에 데이터를 저장합니다. 아래 예제를 통해 실제 사용 방법을 자세히 살펴보겠습니다.
예제 1: Add() 메서드로 요소 추가하기
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의 키와 값 쌍...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Hashtable 항목 수 = "+ hash.Count);
hash.Add("11", "K");
Console.WriteLine("Hashtable의 키와 값 쌍...업데이트됨");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Hashtable 항목 수 (업데이트 후) = "+hash.Count);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Hashtable의 키와 값 쌍... 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 Hashtable 항목 수 = 10 Hashtable의 키와 값 쌍...업데이트됨 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 11 and K Hashtable 항목 수 (업데이트 후) = 11
실행 결과를 보면 Add("11", "K") 메서드 호출 이후 항목 수가 10개에서 11개로 증가한 것을 확인할 수 있습니다. 또한 Hashtable은 내부적으로 해시 알고리즘을 기반으로 요소를 저장하기 때문에, 출력 순서가 입력 순서와 다르게 나타나는 점도 주목할 필요가 있습니다.
예제 2: IDictionaryEnumerator로 Hashtable 반복 처리하기
이번에는 IDictionaryEnumerator를 활용하여 Hashtable의 모든 요소를 순회하는 방법을 살펴보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable(10);
hash.Add("1", "SUV");
hash.Add("2", "Electric Cars");
hash.Add("3", "AUV");
hash.Add("4", "Utility Vehicle");
hash.Add("5","Compact Car");
hash.Add("6", "Sedan");
hash.Add("7","Crossover");
Console.WriteLine("Enumerator를 사용해 Hashtable 반복하기...");
IDictionaryEnumerator demoEnum = hash.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Enumerator를 사용해 Hashtable 반복하기... Key = 1, Value = SUV Key = 2, Value = Electric Cars Key = 3, Value = AUV Key = 4, Value = Utility Vehicle Key = 5, Value = Compact Car Key = 6, Value = Sedan Key = 7, Value = Crossover
정리
C#의 Hashtable에 요소를 추가하는 방법을 두 가지 관점에서 살펴보았습니다. 첫 번째 예제는 Add() 메서드로 여러 개의 키-값 쌍을 추가하고 Count 속성으로 항목 수 변화를 확인했으며, 두 번째 예제는 GetEnumerator() 메서드와 IDictionaryEnumerator 인터페이스를 통해 저장된 데이터를 순회하는 방법을 보여주었습니다. Hashtable은 제네릭이 아닌 컬렉션이므로, 타입 안정성이 중요한 최신 프로젝트에서는 Dictionary<TKey, TValue> 사용도 함께 고려해 보시기 바랍니다.