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

C#에서 GetEnumerator()로 StringDictionary를 반복하는 열거자 가져오기

C#의 StringDictionary 컬렉션은 문자열 형식의 키와 값을 저장하는 특수한 사전 컬렉션입니다. 이 컬렉션의 요소를 하나씩 순회하려면 GetEnumerator() 메서드를 사용하여 IEnumerator 객체를 얻으면 됩니다.

GetEnumerator() 메서드는 StringDictionary 전체를 반복할 수 있는 열거자를 반환합니다. 반환된 열거자는 MoveNext()로 다음 요소로 이동하고, Current 속성으로 현재 요소(DictionaryEntry)에 접근하는 방식으로 사용합니다.

예제 1: foreach 문과 GetEnumerator() 비교

다음 예제는 두 개의 StringDictionary를 생성합니다. 첫 번째 사전은 foreach 문으로 순회하고, 두 번째 사전은 GetEnumerator()로 얻은 열거자를 통해 순회합니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("A", "John");
      strDict1.Add("B", "Andy");
      strDict1.Add("C", "Tim");
      strDict1.Add("D", "Ryan");
      strDict1.Add("E", "Kevin");
      strDict1.Add("F", "Katie");
      strDict1.Add("G", "Brad");

      Console.WriteLine("StringDictionary1 elements...");
      foreach(DictionaryEntry de in strDict1) {
         Console.WriteLine(de.Key + " " + de.Value);
      }

      StringDictionary strDict2 = new StringDictionary();
      strDict2.Add("1", "A");
      strDict2.Add("2", "B");
      strDict2.Add("3", "C");
      strDict2.Add("4", "D");
      strDict2.Add("5", "E");

      Console.WriteLine("\nStringDictionary2 key-value pairs...");
      IEnumerator demoEnum = strDict2.GetEnumerator();
      DictionaryEntry d;
      while (demoEnum.MoveNext()) {
         d = (DictionaryEntry)demoEnum.Current;
         Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
      }
   }
}

출력 결과

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

StringDictionary1 elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad

StringDictionary2 key-value pairs...
Key = 1, Value = A
Key = 2, Value = B
Key = 3, Value = C
Key = 4, Value = D
Key = 5, Value = E

첫 번째 사전의 출력에서 알 수 있듯이, StringDictionary는 내부적으로 해시 테이블 기반으로 동작하기 때문에 추가한 순서와 관계없이 키가 정렬되어 출력될 수 있습니다.

예제 2: GetEnumerator()만 사용하는 경우

이번에는 열거자만을 사용하여 StringDictionary의 모든 키-값 쌍을 순회하는 예제입니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      StringDictionary strDict = new StringDictionary();
      strDict.Add("1", "One");
      strDict.Add("2", "Two");
      strDict.Add("3", "Three");
      strDict.Add("4", "Four");

      Console.WriteLine("StringDictionary key-value pairs...");
      IEnumerator demoEnum = strDict.GetEnumerator();
      DictionaryEntry d;
      while (demoEnum.MoveNext()) {
         d = (DictionaryEntry)demoEnum.Current;
         Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
      }
   }
}

출력 결과

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

StringDictionary key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four

핵심 포인트 정리

  • GetEnumerator() 메서드는 StringDictionary의 모든 요소를 순회할 수 있는 IEnumerator를 반환합니다.
  • 열거자의 Current 속성은 DictionaryEntry 타입이므로 명시적 캐스팅이 필요합니다.
  • MoveNext()가 true를 반환하는 동안 반복하며, 더 이상 요소가 없으면 false를 반환해 루프가 종료됩니다.
  • 열거자는 읽기 전용이므로 순회 중에 컬렉션을 수정하면 InvalidOperationException이 발생할 수 있습니다.