C#에서 Collection<T> 클래스는 GetEnumerator() 메서드를 제공합니다. 이 메서드는 컬렉션의 모든 요소를 순회(iterate)할 수 있는 열거자(Enumerator)를 반환하며, MoveNext()와 Current 속성을 함께 사용해 요소를 하나씩 차례대로 읽어올 수 있습니다.
주요 동작 원리
열거자를 사용하는 기본 흐름은 다음과 같습니다.
GetEnumerator()를 호출하여 열거자 객체를 가져옵니다.MoveNext()가true를 반환하는 동안 반복문을 실행합니다. 이 메서드는 다음 요소로 커서를 이동시킵니다.Current속성으로 현재 위치의 요소 값에 접근합니다.
예제 1: 문자열 컬렉션 순회
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("Andy");
col.Add("Kevin");
col.Add("John");
col.Add("Kevin");
col.Add("Mary");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
col.Add("Mark");
Console.WriteLine("Count of elements = " + col.Count);
Console.WriteLine("Iterating through the collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}실행 결과
Count of elements = 9 Iterating through the collection... Andy Kevin John Kevin Mary Katie Barry Nathan Mark
예제 2: 정수 컬렉션 순회
이번에는 정수형(int) 컬렉션에 대해 같은 방식으로 열거자를 사용해 보겠습니다.
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<int> col = new Collection<int>();
col.Add(100);
col.Add(200);
col.Add(300);
col.Add(400);
col.Add(500);
Console.WriteLine("Count of elements = " + col.Count);
Console.WriteLine("Iterating through the collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}실행 결과
Count of elements = 5 Iterating through the collection... 100 200 300 400 500
정리
GetEnumerator() 메서드는 Collection<T>뿐만 아니라 대부분의 .NET 컬렉션 타입에서 지원됩니다. 참고로 실무에서는 위 예제처럼 열거자를 직접 다루기보다 foreach 문을 사용하는 것이 더 간결하고 안전하지만, 열거자의 내부 동작 방식을 이해하면 컬렉션 순회의 원리를 더 깊이 파악할 수 있습니다.