C#에서 List<T> 클래스가 제공하는 Reverse() 메서드를 사용하면 리스트의 요소 순서를 손쉽게 뒤집을 수 있습니다. 이 메서드는 두 가지 방식으로 사용할 수 있습니다.
- Reverse() – 매개변수 없이 호출하면 리스트 전체 요소의 순서를 반대로 바꿉니다.
- Reverse(int index, int count) – 시작 인덱스와 요소 개수를 지정하여 해당 범위 내의 요소만 역순으로 정렬합니다.
아래 예제들을 통해 각각의 사용법을 살펴보겠습니다.
예제 1: 특정 범위의 요소 순서 뒤집기
다음 코드는 인덱스 2부터 시작하는 4개의 요소만 역순으로 정렬합니다.
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");
Console.WriteLine("열거자를 통해 리스트 요소 출력...");
List<string>.Enumerator demoEnum = list.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
list.Reverse(2, 4);
Console.WriteLine("인덱스 2부터 시작하는 4개 요소를 역순으로 정렬한 결과...");
foreach (string res in list) {
Console.WriteLine(res);
}
}
}
출력 결과
Enumerator iterates through the list elements... One Two Three Four Five Six Seven Eight Elements in ArrayList2...Reversed 4 elements beginning from index 2 One Two Six Five Four Three Seven Eight
실행 결과를 보면 Reverse(2, 4) 호출로 인해 인덱스 2~5에 해당하는 "Three", "Four", "Five", "Six" 네 개의 요소만 "Six", "Five", "Four", "Three"로 순서가 바뀌었고, 나머지 요소는 원래 위치 그대로 유지된 것을 확인할 수 있습니다.
예제 2: 리스트 전체 요소 순서 뒤집기
이번에는 매개변수 없이 Reverse() 메서드를 호출하여 리스트 전체의 순서를 반대로 바꿔보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(5);
list.Add(10);
list.Add(20);
list.Add(50);
list.Add(100);
Console.WriteLine("열거자를 통해 리스트 요소 출력...");
List<int>.Enumerator demoEnum = list.GetEnumerator();
while (demoEnum.MoveNext()) {
int res = demoEnum.Current;
Console.WriteLine(res);
}
list.Reverse();
Console.WriteLine("리스트 전체 요소를 역순으로 정렬한 결과...");
foreach (int i in list) {
Console.WriteLine(i);
}
}
}
출력 결과
Enumerator iterates through the list elements... 5 10 20 50 100 Elements in List...Reversed 100 50 20 10 5
Reverse() 메서드는 리스트 자체를 제자리(in-place)에서 수정하며 새로운 리스트를 반환하지 않는다는 점에 유의하세요. 따라서 원본 리스트의 순서를 유지해야 하는 경우에는 미리 복사본을 만들어 두는 것이 좋습니다. 또한 LINQ의 Enumerable.Reverse() 확장 메서드와 이름이 같지만 동작 방식이 다르므로, 원본 변경 없이 역순 시퀀스가 필요하다면 LINQ 버전을 사용하는 것도 좋은 대안입니다.