C#에서 리스트(List)의 첫 번째 요소를 팝(pop)하려면 RemoveAt() 메서드를 사용하면 됩니다. 이 메서드는 지정한 인덱스 위치에 있는 요소를 삭제하며, 인덱스 0을 전달하면 리스트의 맨 앞 요소가 제거됩니다.
1. 리스트 선언하기
먼저 예제에 사용할 문자열 리스트를 생성합니다.
List<string> myList = new List<string>() {
"Operating System",
"Computer Networks",
"Compiler Design"
};
2. RemoveAt(0)으로 첫 번째 요소 제거하기
RemoveAt()에 인덱스 0을 인자로 넘기면 첫 번째 요소가 삭제됩니다.
myList.RemoveAt(0);
이제 전체 예제 코드를 살펴보겠습니다.
전체 예제 코드
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> myList = new List<string>() {
"Operating System",
"Computer Networks",
"Compiler Design"
};
Console.Write("Initial list...");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Removing first element from the list...");
myList.RemoveAt(0);
foreach (string list in myList) {
Console.WriteLine(list);
}
}
}
출력 결과
Initial list... Operating System Computer Networks Compiler Design Removing first element from the list... Computer Networks Compiler Design
출력 결과를 보면 "Operating System"이 리스트에서 제거되고, 나머지 두 개의 요소만 남은 것을 확인할 수 있습니다.
참고: 성능 관련 팁
List<T>의 RemoveAt(0)은 내부적으로 요소들을 한 칸씩 앞으로 이동시켜야 하므로 O(n) 연산입니다. 만약 첫 번째 요소를 반복적으로 자주 제거해야 하는 상황이라면, FIFO 구조에 특화된 Queue<T>(Dequeue() 메서드 사용) 또는 LinkedList<T>를 사용하는 것이 더 효율적입니다.