C#에서 Collection의 지정된 인덱스에 있는 요소를 제거하려면 RemoveAt() 메서드를 사용합니다. 이 메서드는 0부터 시작하는 인덱스를 매개변수로 받아 해당 위치의 요소를 삭제하고, 그 뒤에 있던 요소들을 자동으로 앞으로 이동시킵니다.
예제 1: 단일 요소 제거하기
다음 예제는 문자열 컬렉션을 생성한 후, 인덱스 3에 위치한 요소를 제거하는 코드입니다.
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("요소 개수 = " + col.Count);
Console.WriteLine("컬렉션 순회 중...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
// 인덱스 3의 요소 제거
col.RemoveAt(3);
Console.WriteLine("요소 개수 (업데이트 후) = " + col.Count);
Console.WriteLine("컬렉션 순회 중... (업데이트 후)");
enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
요소 개수 = 9 컬렉션 순회 중... Andy Kevin John Kevin Mary Katie Barry Nathan Mark 요소 개수 (업데이트 후) = 8 컬렉션 순회 중... (업데이트 후) Andy Kevin John Mary Katie Barry Nathan Mark
인덱스 3(네 번째 위치)에 있던 두 번째 "Kevin"이 제거되고, 전체 요소 개수가 9개에서 8개로 줄어든 것을 확인할 수 있습니다.
예제 2: 여러 요소 연속으로 제거하기
이번에는 RemoveAt() 메서드를 여러 번 호출하여 여러 요소를 제거하는 예제입니다. 주의할 점은 요소가 제거될 때마다 뒤쪽 요소들의 인덱스가 앞으로 당겨진다는 것입니다.
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("One");
col.Add("Two");
col.Add("Three");
col.Add("Four");
col.Add("Five");
col.Add("Six");
Console.WriteLine("요소 개수 = " + col.Count);
Console.WriteLine("컬렉션 순회 중...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
// 인덱스 1, 2, 3의 요소를 차례로 제거
col.RemoveAt(1); // "Two" 제거
col.RemoveAt(2); // "Four" 제거
col.RemoveAt(3); // "Six" 제거
Console.WriteLine("요소 개수 (업데이트 후) = " + col.Count);
Console.WriteLine("컬렉션 순회 중... (업데이트 후)");
enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
요소 개수 = 6 컬렉션 순회 중... One Two Three Four Five Six 요소 개수 (업데이트 후) = 3 컬렉션 순회 중... (업데이트 후) One Three Five
핵심 정리
RemoveAt(int index)메서드는System.Collections.ObjectModel네임스페이스의Collection<T>클래스에서 제공됩니다.- 인덱스는 0부터 시작하므로, 첫 번째 요소를 제거하려면
RemoveAt(0)을 호출해야 합니다. - 유효 범위를 벗어난 인덱스를 전달하면
ArgumentOutOfRangeException이 발생합니다. - 여러 요소를 연속해서 제거할 때는 제거 후 인덱스가 재조정된다는 점을 반드시 고려해야 합니다.