System.Collections.Specialized 네임스페이스에 포함된 StringCollection 클래스에서 지정된 인덱스의 요소를 제거하려면 RemoveAt() 메서드를 사용합니다.
RemoveAt(int index) 메서드는 0부터 시작하는 인덱스를 매개변수로 받아 해당 위치의 문자열을 컬렉션에서 삭제합니다. 요소가 제거되면 뒤쪽에 있던 요소들이 자동으로 한 칸씩 앞으로 이동하며, Count 속성 값도 1만큼 감소합니다. 만약 인덱스가 유효 범위를 벗어나면 ArgumentOutOfRangeException 예외가 발생하므로 주의해야 합니다.
예제 1
다음은 RemoveAt() 메서드를 사용해 특정 인덱스의 요소를 하나 제거하는 기본적인 예제입니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "300", "400", "500" };
Console.WriteLine("Array elements...");
foreach (string res in arr) {
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Total number of elements = "+stringCol.Count);
stringCol.RemoveAt(3);
Console.WriteLine("Total number of elements now = "+stringCol.Count);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Array elements... 100 200 300 400 500 Total number of elements = 5 Total number of elements now = 4
실행 결과를 보면 인덱스 3에 해당하는 네 번째 요소 "400"이 제거되어 전체 요소 수가 5개에서 4개로 줄어든 것을 확인할 수 있습니다.
예제 2
이번에는 RemoveAt() 메서드를 연속으로 호출하여 여러 개의 요소를 차례대로 제거하는 예제를 살펴보겠습니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "A", "B", "C", "D", "E" };
Console.WriteLine("Array elements...");
foreach (string res in arr) {
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Total number of elements = "+stringCol.Count);
stringCol.RemoveAt(1);
stringCol.RemoveAt(2);
Console.WriteLine("Total number of elements now = "+stringCol.Count);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Array elements... A B C D E Total number of elements = 5 Total number of elements now = 3
여기서 중요한 점은 두 번째 RemoveAt(2) 호출 시점입니다. 먼저 인덱스 1의 "B"가 제거되면 컬렉션은 ["A", "C", "D", "E"] 상태가 되고, 이후 RemoveAt(2)는 변경된 컬렉션 기준으로 인덱스 2의 "D"를 제거합니다. 따라서 최종적으로 남는 요소는 "A", "C", "E" 세 개입니다.