C#의 List<T> 컬렉션은 요소를 삭제할 수 있는 다양한 메서드를 제공합니다. 대표적으로 Remove(), RemoveAt(), RemoveRange() 세 가지가 있으며, 각각의 용도는 다음과 같습니다.
- Remove(): 지정한 값을 가진 첫 번째 요소를 찾아 제거합니다.
- RemoveAt(): 지정한 인덱스(위치)에 있는 요소를 제거합니다.
- RemoveRange(): 시작 인덱스부터 지정한 개수만큼의 요소를 한 번에 제거합니다.
Remove()와 RemoveAt() 사용 예제
먼저 문자열 리스트를 생성합니다.
List<string> myList = new List<string>() {
"mammals",
"reptiles",
"amphibians",
"vertebrate"
};Remove() 메서드를 사용하면 특정 값을 가진 요소를 삭제할 수 있습니다.
myList.Remove("reptiles");RemoveAt() 메서드는 인덱스를 지정하여 해당 위치의 요소를 삭제합니다. 아래 코드는 인덱스 2에 있는 요소를 제거합니다.
myList.RemoveAt(2);
다음은 두 메서드를 모두 활용한 전체 코드입니다.
예제 코드
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> myList = new List<string>() {
"mammals",
"reptiles",
"amphibians",
"vertebrate"
};
Console.Write("Initial list...");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Using Remove() method...");
myList.Remove("reptiles");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Using RemoveAt() method...");
myList.RemoveAt(2);
foreach (string list in myList) {
Console.WriteLine(list);
}
}
}RemoveRange() 사용 예제
RemoveRange(int index, int count)는 시작 인덱스부터 지정한 개수만큼의 요소를 연속으로 제거합니다. 다음 예제는 리스트 앞부분의 요소들을 일괄 삭제하는 방법을 보여줍니다.
예제 코드
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<int> myList = new List<int>();
myList.Add(5);
myList.Add(10);
myList.Add(15);
myList.Add(20);
myList.Add(25);
myList.Add(30);
myList.Add(35);
Console.Write("Initial list...");
foreach (int list in myList) {
Console.WriteLine(list);
}
Console.Write("New list...");
int rem = Math.Max(0, myList.Count - 3);
myList.RemoveRange(0, rem);
foreach (int list in myList) {
Console.Write("\n" + list);
}
}
}정리
값 기준으로 삭제하려면 Remove(), 위치 기준으로 하나의 요소를 삭제하려면 RemoveAt(), 여러 요소를 한꺼번에 삭제하려면 RemoveRange()를 사용하면 됩니다. 상황에 맞는 메서드를 선택하면 리스트 데이터를 더욱 효율적으로 관리할 수 있습니다.