C#에서 List에 저장된 특정 항목을 삭제하려면 Remove() 메서드를 사용하면 됩니다. Remove() 메서드는 지정한 요소와 일치하는 첫 번째 항목을 리스트에서 제거합니다.
1. 리스트 생성 및 요소 추가
먼저 리스트를 생성하고 요소를 추가합니다.
List<string> myList = new List<string>();
myList.Add("Jennings");
myList.Add("James");
myList.Add("Chris");2. Remove() 메서드로 요소 제거하기
예를 들어, 리스트에서 "James"라는 요소를 삭제해야 한다고 가정해 보겠습니다. 이때 Remove() 메서드를 사용하면 간단하게 처리할 수 있습니다.
myList.Remove("James");Remove() 메서드는 제거할 요소를 찾으면 true를 반환하고, 해당 요소가 리스트에 존재하지 않으면 false를 반환합니다.
전체 예제 코드
using System.Collections.Generic;
using System;
class Program {
static void Main() {
List<string> myList = new List<string>();
myList.Add("Jennings");
myList.Add("James");
myList.Add("Chris");
Console.WriteLine("초기 리스트...");
foreach(string str in myList) {
Console.WriteLine(str);
}
// "James" 요소 제거
myList.Remove("James");
Console.WriteLine("제거 후 리스트...");
foreach(string str in myList) {
Console.WriteLine(str);
}
}
}실행 결과
초기 리스트... Jennings James Chris 제거 후 리스트... Jennings Chris
참고: 다른 제거 메서드들
상황에 따라 아래와 같은 메서드도 활용할 수 있습니다.
- RemoveAt(int index): 인덱스 위치의 요소를 제거합니다.
- RemoveAll(Predicate<T>): 조건에 맞는 모든 요소를 한 번에 제거합니다.
- Clear(): 리스트의 모든 요소를 제거합니다.
이처럼 C#의 List<T> 클래스는 다양한 제거 메서드를 제공하여 컬렉션을 유연하게 관리할 수 있습니다.