C#에서 StringDictionary는 System.Collections.Specialized 네임스페이스에 속한 컬렉션 클래스로, 키(Key)와 값(Value)이 모두 문자열인 해시 테이블입니다. 일반적인 Hashtable과 달리 문자열 전용으로 최적화되어 있어 박싱(boxing) 오버헤드 없이 데이터를 다룰 수 있다는 장점이 있습니다.
StringDictionary 생성하기
StringDictionary 객체는 new 키워드로 간단히 생성할 수 있으며, Add() 메서드를 사용해 키와 값을 추가합니다.
예제
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringDictionary strDict = new StringDictionary();
strDict.Add("A", "John");
strDict.Add("B", "Andy");
strDict.Add("C", "Tim");
strDict.Add("D", "Ryan");
strDict.Add("E", "Kevin");
strDict.Add("F", "Katie");
strDict.Add("G", "Brad");
Console.WriteLine("StringDictionary elements...");
foreach(DictionaryEntry de in strDict) {
Console.WriteLine(de.Key + " " + de.Value);
}
}
}출력 결과
StringDictionary elements... a John b Andy c Tim d Ryan e Kevin f Katie g Brad
출력 결과를 보면 입력 시 대문자였던 키(A, B, C...)가 모두 소문자(a, b, c...)로 변환된 것을 확인할 수 있습니다. StringDictionary는 기본적으로 키를 소문자로 변환해 저장하며, 키 조회 시에도 대소문자를 구분하지 않습니다.
인덱서로 특정 키의 값 가져오기
인덱서([])를 사용하면 특정 키에 해당하는 값을 간편하게 조회할 수 있습니다.
예제
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringDictionary myDict = new StringDictionary();
myDict.Add("1", "Tablet");
myDict.Add("2", "Desktop");
myDict.Add("3", "Speakers");
myDict.Add("4", "Laptop");
myDict.Add("5", "Notebook");
myDict.Add("6", "Ultrabook");
myDict.Add("7", "HDD");
myDict.Add("8", "SDD");
myDict.Add("9", "Headphone");
myDict.Add("10", "Earphone");
Console.WriteLine("Value for key 5 = " + myDict["5"]);
}
}출력 결과
Value for key 5 = Notebook
위 예제에서는 myDict["5"]처럼 인덱서를 활용해 키 "5"에 매핑된 값 "Notebook"을 성공적으로 가져왔습니다. 이처럼 StringDictionary는 문자열 기반 키-값 쌍을 관리할 때 유용하게 활용할 수 있습니다.