Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# ListDictionary를 반복하는 열거자(Enumerator) 가져오는 방법

C#에서 ListDictionary의 요소를 반복(iterate)하려면 GetEnumerator() 메서드를 사용하면 됩니다. 이 메서드는 IDictionaryEnumerator 인터페이스를 반환하며, MoveNext() 메서드를 호출할 때마다 다음 요소로 이동하면서 컬렉션에 저장된 모든 키-값 쌍을 순차적으로 탐색할 수 있습니다.

열거자가 반환되는 초기 위치는 컬렉션의 첫 번째 요소 앞이므로, 반드시 MoveNext()를 먼저 호출해야 첫 번째 요소에 접근할 수 있다는 점도 기억해 두면 좋습니다.

예제

다음 예제에서는 두 개의 ListDictionary 객체를 생성합니다. 첫 번째 딕셔너리는 foreach 문으로 반복하고, 두 번째 딕셔너리는 GetEnumerator() 메서드로 얻은 열거자를 통해 반복합니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
    public static void Main(){
        ListDictionary dict1 = new ListDictionary();
        dict1.Add("A", "Books");
        dict1.Add("B", "Electronics");
        dict1.Add("C", "Smart Wearables");
        dict1.Add("D", "Pet Supplies");
        dict1.Add("E", "Clothing");
        dict1.Add("F", "Footwear");
        Console.WriteLine("ListDictionary1 elements...");
        foreach(DictionaryEntry d in dict1){
            Console.WriteLine(d.Key + " " + d.Value);
        }
        ListDictionary dict2 = new ListDictionary();
        dict2.Add("1", "One");
        dict2.Add("2", "Two");
        dict2.Add("3", "Three");
        dict2.Add("4", "Four");
        dict2.Add("5", "Five");
        dict2.Add("6", "Six");
        Console.WriteLine("\nListDictionary2 key-value pairs...");
        IDictionaryEnumerator demoEnum = dict2.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
    }
}

출력

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

ListDictionary1 elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear

ListDictionary2 key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six

예제 2

이번에는 GetEnumerator() 메서드로 얻은 열거자만을 사용하여 ListDictionary의 모든 키-값 쌍을 출력하는 또 다른 예제를 살펴보겠습니다. while 루프 안에서 MoveNext()true를 반환하는 동안 계속 반복하며, 더 이상 요소가 없으면 루프가 종료됩니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
    public static void Main(){
        ListDictionary dict = new ListDictionary();
        dict.Add("1", "One");
        dict.Add("2", "Two");
        dict.Add("3", "Three");
        dict.Add("4", "Four");
        dict.Add("5", "Five");
        dict.Add("6", "Six");
        Console.WriteLine("ListDictionary key-value pairs...");
        IDictionaryEnumerator demoEnum = dict.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
    }
}

출력

실행 결과는 다음과 같습니다.

ListDictionary key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six

핵심 정리

  • GetEnumerator()는 ListDictionary를 순회할 수 있는 IDictionaryEnumerator를 반환합니다.
  • MoveNext()를 호출해야 다음 요소로 이동하며, 마지막 요소를 지나면 false를 반환합니다.
  • 현재 위치한 요소의 키와 값은 각각 Key, Value 속성으로 접근할 수 있습니다.
  • 요소 개수가 적은 경우 ListDictionary는 내부적으로 단일 연결 리스트를 사용하기 때문에 작은 컬렉션에서 효율적입니다.