C#의 ArrayList 클래스에서 특정 범위의 요소를 한 번에 제거하려면 RemoveRange() 메서드를 사용합니다. 이 메서드는 시작 인덱스와 제거할 요소의 개수를 인자로 받아, 해당 범위에 속한 요소들을 일괄 삭제합니다.
RemoveRange() 메서드 구문
public virtual void RemoveRange (int index, int count);
- index: 제거를 시작할 요소의 인덱스 (0부터 시작)
- count: 제거할 요소의 개수
예제 1
다음 예제는 ArrayList에서 요소 범위를 제거하는 방법을 보여줍니다 −
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args){
ArrayList list1 = new ArrayList();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
list1.Add("E");
list1.Add("F");
list1.Add("G");
list1.Add("H");
list1.Add("I");
Console.WriteLine("ArrayList1의 요소...");
foreach (string res in list1){
Console.WriteLine(res);
}
ArrayList list2 = new ArrayList();
list2.Add("A");
list2.Add("B");
list2.Add("C");
list2.Add("D");
list2.Add("E");
list2.Add("F");
list2.Add("G");
list2.Add("H");
list2.Add("I");
Console.WriteLine("ArrayList2의 요소...");
foreach (string res in list2){
Console.WriteLine(res);
}
Console.WriteLine("ArrayList1과 ArrayList2가 같습니까? = "+list1.Equals(list2));
list2.RemoveRange(3, 2);
Console.WriteLine("범위 내 요소를 제거한 후 ArrayList2의 요소...");
foreach (string res in list2){
Console.WriteLine(res);
}
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
ArrayList1의 요소... A B C D E F G H I ArrayList2의 요소... A B C D E F G H I ArrayList1과 ArrayList2가 같습니까? = False 범위 내 요소를 제거한 후 ArrayList2의 요소... A B C F G H I
여기서 list2.RemoveRange(3, 2)는 인덱스 3부터 시작하여 2개의 요소, 즉 "D"(인덱스 3)와 "E"(인덱스 4)를 제거합니다. 그 결과 리스트에는 A, B, C, F, G, H, I만 남게 됩니다.
예제 2
이번에는 다른 예제를 살펴보겠습니다 −
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args){
ArrayList list1 = new ArrayList();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");
list1.Add("E");
list1.Add("F");
list1.Add("G");
list1.Add("H");
list1.Add("I");
Console.WriteLine("ArrayList1의 요소...");
foreach (string res in list1){
Console.WriteLine(res);
}
ArrayList list2 = new ArrayList();
list2.Add("One");
list2.Add("Two");
list2.Add("Three");
list2.Add("Four");
list2.Add("Five");
list2.Add("Six");
list2.Add("Seven");
Console.WriteLine("ArrayList2의 요소...");
foreach (string res in list2){
Console.WriteLine(res);
}
list2.RemoveRange(1, 6);
Console.WriteLine("범위 내 요소를 제거한 후 ArrayList2의 요소...");
foreach (string res in list2){
Console.WriteLine(res);
}
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
ArrayList1의 요소... A B C D E F G H I ArrayList2의 요소... One Two Three Four Five Six Seven 범위 내 요소를 제거한 후 ArrayList2의 요소... One
이 예제에서 list2.RemoveRange(1, 6)은 인덱스 1부터 6개의 요소, 즉 "Two"부터 "Seven"까지를 모두 제거합니다. 따라서 최종적으로 리스트에는 첫 번째 요소인 "One"만 남게 됩니다.