C#의 OrderedDictionary 컬렉션에서 IDictionaryEnumerator 개체를 가져오려면 GetEnumerator() 메서드를 사용합니다. IDictionaryEnumerator는 사전(Dictionary) 형태의 컬렉션을 순회할 수 있도록 지원하는 인터페이스로, 일반 열거자와 달리 현재 요소의 키(Key)와 값(Value)에 각각 접근할 수 있다는 장점이 있습니다.
아래 예제에서는 OrderedDictionary에 여러 항목을 추가한 뒤, IDictionaryEnumerator를 이용해 전체 요소를 순회하면서 키와 값을 출력해 보겠습니다.
예제 1
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("1", "One");
dict.Add("2", "Two");
dict.Add("3", "Three");
dict.Add("4", "Four");
dict.Add("5", "Five");
dict.Add("6", "Six");
dict.Add("7", "Seven");
dict.Add("8", "Eight");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
while (demoEnum.MoveNext()) {
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Key = 1, Value = One Key = 2, Value = Two Key = 3, Value = Three Key = 4, Value = Four Key = 5, Value = Five Key = 6, Value = Six Key = 7, Value = Seven Key = 8, Value = Eight
코드 설명
- GetEnumerator() – OrderedDictionary의 모든 요소를 순회할 수 있는 IDictionaryEnumerator 개체를 반환합니다.
- MoveNext() – 열거자를 컬렉션의 다음 요소로 이동시킵니다. 더 이상 요소가 없으면 false를 반환하여 while 루프가 종료됩니다.
- Key / Value – 열거자가 현재 가리키는 요소의 키와 값을 각각 반환합니다.
참고: OrderedDictionary는 System.Collections.Specialized 네임스페이스에 포함된 컬렉션으로, 요소가 삽입된 순서를 그대로 유지합니다. 따라서 출력 결과에서 확인할 수 있듯이 항목을 추가한 순서대로 키와 값이 조회됩니다.
예제 2
이번에는 카테고리 정보를 저장하는 OrderedDictionary를 순회하는 예제입니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("1", "Appliances");
dict.Add("2", "Supplies");
dict.Add("3", "Electronics");
dict.Add("4", "Clothing");
dict.Add("5", "Books");
dict.Add("6", "Accessories");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
while (demoEnum.MoveNext()) {
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
}
}
출력 결과
실행하면 아래와 같은 결과를 얻을 수 있습니다.
Key = 1, Value = Appliances Key = 2, Value = Supplies Key = 3, Value = Electronics Key = 4, Value = Clothing Key = 5, Value = Books Key = 6, Value = Accessories
정리
OrderedDictionary에서 IDictionaryEnumerator 개체가 필요하다면 GetEnumerator() 메서드를 호출하기만 하면 됩니다. 반환된 열거자의 MoveNext() 메서드와 Key, Value 속성을 함께 사용하면 삽입 순서를 기준으로 사전의 모든 항목을 손쉽게 순회하고 처리할 수 있습니다.