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

C# GetEnumerator() 메서드로 List를 반복하는 열거자(Enumerator) 가져오기

C#에서 List<T> 컬렉션의 모든 요소를 순차적으로 반복(iterate)하려면 GetEnumerator() 메서드를 사용하여 열거자(Enumerator)를 가져올 수 있습니다. 반환된 List<String>.Enumerator 객체의 MoveNext() 메서드와 Current 속성을 조합하면 foreach 문 없이도 리스트의 각 요소에 접근할 수 있습니다.

동작 원리

  • GetEnumerator(): 리스트를 반복하는 열거자를 반환합니다.
  • MoveNext(): 다음 요소로 이동하며, 더 이상 요소가 없으면 false를 반환합니다.
  • Current: 현재 위치의 요소 값을 가져옵니다.

예제 1

두 개의 리스트를 만들고, 두 번째 리스트에는 GetEnumerator()로 얻은 열거자를 사용해 요소를 출력하는 예제입니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<String> list1 = new List<String>();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");
      list1.Add("Five");
      Console.WriteLine("Elements in List1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      List<String> list2 = new List<String>();
      list2.Add("India");
      list2.Add("US");
      list2.Add("UK");
      list2.Add("Canada");
      list2.Add("Poland");
      list2.Add("Netherlands");
      Console.WriteLine("Elements in List2...");
      List<String>.Enumerator demoEnum = list2.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
      Console.WriteLine("Is List2 equal to List1? = "+list2.Equals(list1));
   }
}

출력 결과

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

Elements in List1...
One
Two
Three
Four
Five
Elements in List2...
India
US
UK
Canada
Poland
Netherlands
Is List2 equal to List1? = False

예제 2

이번에는 하나의 리스트에 10개의 요소를 추가한 뒤, 열거자를 이용해 전체 요소를 순회하는 또 다른 예제입니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<String> list = new List<String>();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      list.Add("Six");
      list.Add("Seven");
      list.Add("Eight");
      list.Add("Nine");
      list.Add("Ten");
      Console.WriteLine("Enumerator iterates through the list elements...");
      List<String>.Enumerator demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}

출력 결과

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

Enumerator iterates through the list elements...
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
Ten

정리

이처럼 C#의 GetEnumerator() 메서드를 활용하면 리스트를 반복하는 열거자를 손쉽게 얻을 수 있으며, while 루프와 MoveNext(), Current를 조합해 요소를 유연하게 순회할 수 있습니다. 일반적인 경우에는 foreach 문이 내부적으로 동일한 방식으로 동작하므로 더 간결하지만, 열거자를 직접 제어해야 하는 상황에서는 GetEnumerator()가 유용합니다.