Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# ArrayList에서 RemoveAt()로 특정 인덱스의 요소 제거하기

C#의 ArrayList에서 지정된 인덱스에 있는 요소를 제거하려면 RemoveAt() 메서드를 사용합니다. 이 메서드는 0부터 시작하는 인덱스를 매개변수로 받아 해당 위치의 요소를 삭제하며, 요소가 제거된 후에는 뒤에 있던 요소들이 자동으로 한 칸씩 앞으로 이동합니다.

만약 전달한 인덱스가 유효 범위(0 ~ Count-1)를 벗어나면 ArgumentOutOfRangeException이 발생하므로 주의해야 합니다.

예제 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("Elements in 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("Elements in ArrayList2...");
      foreach (string res in list2)
      {
         Console.WriteLine(res);
      }
      Console.WriteLine("Count of elements in ArrayList2 = " + list2.Count);
      list2.RemoveAt(5);
      Console.WriteLine("Count of elements in ArrayList2 (Updated) = " + list2.Count);
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Elements in ArrayList1...
A
B
C
D
E
F
G
H
I
Elements in ArrayList2...
A
B
C
D
E
F
G
H
I
Count of elements in ArrayList2 = 9
Count of elements in ArrayList2 (Updated) = 8

인덱스 5에 있던 요소 "F"가 제거되면서 전체 요소 개수가 9개에서 8개로 줄어든 것을 확인할 수 있습니다.

예제 2

이번에는 문자열 데이터를 담은 ArrayList에서 두 번째 인덱스의 요소를 제거해 보겠습니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      ArrayList list1 = new ArrayList();
      list1.Add("Laptop");
      list1.Add("Dektop");
      list1.Add("Wearables");
      list1.Add("Tablet");
      list1.Add("Notebook");
      list1.Add("Ultrabooks");
      Console.WriteLine("Elements in ArrayList1...");
      foreach (string res in list1) {
         Console.WriteLine(res);
      }
      Console.WriteLine("Count of elements in ArrayList = " + list1.Count);
      list1.RemoveAt(2);
      Console.WriteLine("Count of elements in ArrayList (Updated) = " + list1.Count);
   }
}

출력 결과

실행 결과는 다음과 같습니다.

Elements in ArrayList1...
Laptop
Dektop
Wearables
Tablet
Notebook
Ultrabooks
Count of elements in ArrayList = 6
Count of elements in ArrayList (Updated) = 5

인덱스 2에 위치한 "Wearables" 항목이 삭제되고, 요소 개수가 6개에서 5개로 변경되었습니다. 이처럼 RemoveAt() 메서드를 활용하면 ArrayList에서 원하는 위치의 요소를 간단하게 제거할 수 있습니다.