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

C# SortedDictionary 열거자 가져오기 – GetEnumerator()로 키-값 쌍 순회하기

C#에서 SortedDictionary에 저장된 키-값 쌍을 하나씩 순회하고 싶다면 GetEnumerator() 메서드를 사용해 열거자(enumerator)를 가져오면 됩니다. 이 메서드는 컬렉션의 각 요소를 차례대로 탐색할 수 있는 열거자를 반환하며, MoveNext() 메서드와 Current 속성을 조합해 데이터를 순서대로 읽어올 수 있습니다.


SortedDictionary는 항상 키를 기준으로 정렬된 상태를 유지하는 컬렉션이므로, 열거자로 순회할 때에도 키가 오름차순으로 정렬된 순서대로 요소가 반환됩니다.


예제 1: 문자열 값을 가진 SortedDictionary 순회하기


아래 예제에서는 키가 int, 값이 string인 SortedDictionary를 만들고, GetEnumerator()로 열거자를 가져와 모든 키-값 쌍을 출력합니다.


using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Mobile");
      sortedDict.Add(200, "Laptop");
      sortedDict.Add(300, "Desktop");
      sortedDict.Add(400, "Speakers");
      sortedDict.Add(500, "Headphone");
      sortedDict.Add(600, "Earphone");

      Console.WriteLine("SortedDictionary 키-값 쌍...");

      // GetEnumerator()로 열거자를 가져옵니다.
      var demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Current.Key + ", Value = " + demoEnum.Current.Value);
   }
}

실행 결과


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


SortedDictionary 키-값 쌍...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone

예제 2: 정수 값을 가진 SortedDictionary 순회하기


이번에는 값의 자료형이 int인 경우입니다. 같은 방식으로 열거자를 가져와 10개의 키-값 쌍을 순회합니다.


using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      SortedDictionary<int, int> sortedDict = new SortedDictionary<int, int>();
      sortedDict.Add(100, 1);
      sortedDict.Add(200, 2);
      sortedDict.Add(300, 3);
      sortedDict.Add(400, 4);
      sortedDict.Add(500, 5);
      sortedDict.Add(600, 6);
      sortedDict.Add(700, 7);
      sortedDict.Add(800, 8);
      sortedDict.Add(900, 9);
      sortedDict.Add(1000, 10);

      Console.WriteLine("SortedDictionary 키-값 쌍...");

      var demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Current.Key + ", Value = " + demoEnum.Current.Value);
   }
}

실행 결과


SortedDictionary 키-값 쌍...
Key = 100, Value = 1
Key = 200, Value = 2
Key = 300, Value = 3
Key = 400, Value = 4
Key = 500, Value = 5
Key = 600, Value = 6
Key = 700, Value = 7
Key = 800, Value = 8
Key = 900, Value = 9
Key = 1000, Value = 10

정리 및 참고 사항


  • GetEnumerator()는 SortedDictionary의 모든 키-값 쌍을 처음부터 끝까지 탐색할 수 있는 열거자를 반환합니다.
  • SortedDictionary는 키를 기준으로 오름차순 정렬을 유지하므로, 열거자의 순회 순서 역시 정렬된 순서를 따릅니다.
  • 실무에서는 아래와 같이 foreach 문을 사용하는 것이 더 간결하고 안전합니다. foreach는 내부적으로 동일한 열거자 패턴을 사용합니다.
    foreach (KeyValuePair<int, string> pair in sortedDict) {
       Console.WriteLine($"Key = {pair.Key}, Value = {pair.Value}");
    }
  • 열거자는 읽기 전용이며, 순회 도중 컬렉션에 요소를 추가하거나 삭제하면 InvalidOperationException이 발생할 수 있으므로 주의해야 합니다.