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

C# SortedList에서 특정 인덱스의 요소 제거하기: RemoveAt() 메서드 활용법

C#의 SortedList는 키를 기준으로 자동 정렬되는 키-값 쌍 컬렉션입니다. 이 컬렉션에서 지정된 인덱스 위치에 있는 요소를 제거하려면 RemoveAt() 메서드를 사용합니다. 이 메서드는 매개변수로 전달된 인덱스에 해당하는 키-값 쌍을 삭제하고, 이후의 요소들은 자동으로 앞당겨집니다.

RemoveAt() 메서드 개요

RemoveAt(int index) 메서드는 0부터 시작하는 인덱스를 받아 해당 위치의 요소를 제거합니다. 만약 인덱스가 유효 범위(0 이상, Count 미만)를 벗어나면 ArgumentOutOfRangeException이 발생하므로 주의해야 합니다.

예제 1: 단일 요소 제거하기

다음 예제에서는 알파벳 A부터 J까지의 키를 가진 SortedList를 생성한 후, 인덱스 3에 위치한 요소를 제거합니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      SortedList sortedList = new SortedList();
      sortedList.Add("A", "1");
      sortedList.Add("B", "2");
      sortedList.Add("C", "3");
      sortedList.Add("D", "4");
      sortedList.Add("E", "5");
      sortedList.Add("F", "6");
      sortedList.Add("G", "7");
      sortedList.Add("H", "8");
      sortedList.Add("I", "9");
      sortedList.Add("J", "10");
      Console.WriteLine("SortedList elements...");
      foreach(DictionaryEntry d in sortedList) {
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("Count of SortedList key-value pairs = "+sortedList.Count);
      sortedList.RemoveAt(3);
      Console.WriteLine("\nEnumerator to iterate through the SortedList...");
      IDictionaryEnumerator demoEnum = sortedList.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedList key-value pairs (Updated) = "+sortedList.Count);
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다.

SortedList elements...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs = 10

Enumerator to iterate through the SortedList...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs (Updated) = 9

결과 분석: SortedList는 키를 기준으로 오름차순 정렬되므로 인덱스 0은 'A', 1은 'B', 2는 'C', 3은 'D'에 해당합니다. 따라서 RemoveAt(3) 호출 시 키가 'D'인 요소가 제거되었고, 전체 요소 수도 10개에서 9개로 줄어든 것을 확인할 수 있습니다.

예제 2: 여러 요소 연속 제거하기

이번에는 여러 개의 요소를 연속해서 제거하는 예제를 살펴보겠습니다. 문자열 키를 사용할 경우 사전순으로 정렬된다는 점에 유의하세요.

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      SortedList sortedList = new SortedList();
      sortedList.Add("One", "Mouse");
      sortedList.Add("Two", "Keyboard");
      sortedList.Add("Three", "Headphone");
      sortedList.Add("Four", "Speakers");
      sortedList.Add("Five", "RAM");
      Console.WriteLine("SortedList elements...");
      foreach(DictionaryEntry d in sortedList) {
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("Count of SortedList key-value pairs = "+sortedList.Count);
      sortedList.RemoveAt(1);
      sortedList.RemoveAt(2);
      Console.WriteLine("\nEnumerator to iterate through the SortedList...");
      IDictionaryEnumerator demoEnum = sortedList.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("Count of SortedList key-value pairs (Updated) = "+sortedList.Count);
   }
}

실행 결과

SortedList elements...
Key = Five, Value = RAM
Key = Four, Value = Speakers
Key = One, Value = Mouse
Key = Three, Value = Headphone
Key = Two, Value = Keyboard
Count of SortedList key-value pairs = 5

Enumerator to iterate through the SortedList...
Key = Five, Value = RAM
Key = One, Value = Mouse
Key = Two, Value = Keyboard
Count of SortedList key-value pairs (Updated) = 3

결과 분석: 키가 사전순으로 정렬되어 실제 저장 순서는 Five(0), Four(1), One(2), Three(3), Two(4)입니다. 첫 번째 RemoveAt(1) 호출로 'Four'가 제거되면 목록은 Five(0), One(1), Three(2), Two(3)로 재정렬됩니다. 이후 두 번째 RemoveAt(2) 호출 시 인덱스 2에 해당하는 'Three'가 제거되어 최종적으로 3개의 요소만 남게 됩니다.

정리 및 주의사항

  • RemoveAt()은 인덱스 기반 삭제, Remove()는 키 기반 삭제라는 점을 구분해야 합니다.
  • 요소가 제거되면 뒤쪽 요소들의 인덱스가 하나씩 앞으로 당겨지므로, 반복문 내에서 연속 삭제 시 인덱스 변화에 유의해야 합니다.
  • 유효하지 않은 인덱스를 전달하면 ArgumentOutOfRangeException 예외가 발생합니다.
  • SortedList는 삽입 순서가 아닌 키의 정렬 순서로 저장되므로, 인덱스를 계산할 때 항상 정렬된 순서를 기준으로 해야 합니다.