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

C# List에서 특정 인덱스의 요소를 제거하는 방법

C#에서 List의 지정된 인덱스에 있는 요소를 제거하려면 RemoveAt() 메서드를 사용하면 됩니다. 이 메서드는 전달된 인덱스 위치의 요소를 삭제하고, 그 뒤에 있던 요소들을 자동으로 앞으로 이동시켜 줍니다.

RemoveAt() 메서드를 사용하는 방법을 예제와 함께 살펴보겠습니다.

예제 1: 문자열 리스트에서 요소 제거하기

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list = new List<string>();
      list.Add("Ryan");
      list.Add("Kevin");
      list.Add("Andre");
      list.Add("Tom");
      list.Add("Fred");
      list.Add("Jason");
      list.Add("Jacob");
      list.Add("David");
      Console.WriteLine("Count of elements in the List = "+list.Count);
      Console.WriteLine("Enumerator iterates through the list elements...");
      List<string>.Enumerator demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
      list.RemoveAt(5);
      Console.WriteLine("\nCount of elements in the List [UPDATED] = "+list.Count);
      Console.WriteLine("Enumerator iterates through the list elements...[UPDATED]");
      demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}

출력 결과

Count of elements in the List = 8
Enumerator iterates through the list elements...
Ryan
Kevin
Andre
Tom
Fred
Jason
Jacob
David

Count of elements in the List [UPDATED] = 7
Enumerator iterates through the list elements...[UPDATED]
Ryan
Kevin
Andre
Tom
Fred
Jacob
David

위 예제에서는 8개의 이름이 담긴 문자열 리스트를 생성한 뒤, RemoveAt(5)를 호출하여 인덱스 5에 위치한 "Jason"이라는 요소를 제거했습니다. 실행 결과 리스트의 개수가 8개에서 7개로 줄어든 것을 확인할 수 있습니다.

예제 2: 정수 리스트에서 요소 제거하기

이번에는 정수형 리스트에서 요소를 제거하는 또 다른 예제입니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<int> list = new List<int>();
      list.Add(25);
      list.Add(50);
      list.Add(75);
      list.Add(100);
      list.Add(200);
      Console.WriteLine("Count of elements in the List = "+list.Count);
      list.RemoveAt(2);
      Console.WriteLine("\nCount of elements in the List [UPDATED] = "+list.Count);
   }
}

출력 결과

Count of elements in the List = 5
Count of elements in the List [UPDATED] = 4

이 예제에서는 5개의 정수가 담긴 리스트에서 RemoveAt(2)를 호출하여 인덱스 2의 값인 75를 제거했습니다. 결과적으로 리스트의 요소 개수가 5개에서 4개로 변경되었습니다.

참고 사항

RemoveAt() 메서드 사용 시 주의할 점은 다음과 같습니다.

  • 인덱스는 0부터 시작합니다. 즉, 첫 번째 요소의 인덱스는 0입니다.
  • 리스트 범위를 벗어난 인덱스를 전달하면 ArgumentOutOfRangeException 예외가 발생합니다.
  • 요소가 제거되면 해당 위치 이후의 요소들이 한 칸씩 앞으로 이동하며, 리스트의 Count 값도 1 감소합니다.