C#에서 Dictionary 컬렉션의 모든 키-값 쌍을 순회하려면 GetEnumerator() 메서드를 사용하여 열거자(Enumerator)를 가져올 수 있습니다. 반환된 IDictionaryEnumerator 객체는 MoveNext() 메서드를 통해 각 요소로 이동하며, Key와 Value 속성으로 현재 항목의 키와 값을 읽어옵니다.
예제 1: 정수형 키를 가진 Dictionary
다음 예제에서는 int 타입의 키와 string 타입의 값을 가지는 Dictionary를 생성한 후, 열거자를 이용해 모든 요소를 출력합니다.
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(100, "Laptop");
dict.Add(150, "Desktop");
dict.Add(200, "Earphone");
dict.Add(300, "Tablet");
dict.Add(500, "Speakers");
dict.Add(750, "HardDisk");
dict.Add(1000, "SSD");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
Console.WriteLine("열거자가 키-값 쌍을 순회합니다...");
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
}출력 결과
열거자가 키-값 쌍을 순회합니다... Key = 100, Value = Laptop Key = 150, Value = Desktop Key = 200, Value = Earphone Key = 300, Value = Tablet Key = 500, Value = Speakers Key = 750, Value = HardDisk Key = 1000, Value = SSD
예제 2: 문자열 키를 가진 Dictionary
이번에는 키와 값이 모두 문자열인 Dictionary를 열거자로 순회하는 예제입니다.
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Laptop");
dict.Add("Two", "Desktop");
dict.Add("Three", "Earphone");
dict.Add("Four", "Tablet");
dict.Add("Five", "Speakers");
dict.Add("Six", "HardDisk");
dict.Add("Seven", "SSD");
dict.Add("Eight", "Keyboard");
dict.Add("Nine", "Mouse");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
Console.WriteLine("열거자가 키-값 쌍을 순회합니다...");
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
}출력 결과
열거자가 키-값 쌍을 순회합니다... Key = One, Value = Laptop Key = Two, Value = Desktop Key = Three, Value = Earphone Key = Four, Value = Tablet Key = Five, Value = Speakers Key = Six, Value = HardDisk Key = Seven, Value = SSD Key = Eight, Value = Keyboard Key = Nine, Value = Mouse
핵심 포인트
GetEnumerator()메서드는 Dictionary의 요소를 순회할 수 있는IDictionaryEnumerator를 반환합니다.MoveNext()는 다음 요소로 이동하며, 더 이상 요소가 없으면 false를 반환합니다.Key및Value속성으로 현재 위치의 키와 값을 각각 조회할 수 있습니다.- Dictionary의 요소 순서는 보장되지 않으므로, 특정 순서가 필요하다면 별도의 정렬 처리가 필요합니다.