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

C# OrderedDictionary에서 지정된 인덱스의 항목 제거 방법


OrderedDictionary에서 특정 인덱스의 항목 제거하기

C#의 OrderedDictionary는 항목이 추가된 순서를 그대로 유지하는 키-값 컬렉션입니다. 각 항목은 0부터 시작하는 인덱스로 접근할 수 있으며, 지정된 인덱스에 있는 항목을 제거하려면 RemoveAt(int index) 메서드를 사용하면 됩니다.

RemoveAt() 메서드는 해당 위치의 키-값 쌍을 삭제하고, 뒤에 있던 항목들을 자동으로 한 칸씩 앞으로 이동시킵니다. 단, 인덱스가 유효 범위를 벗어나면 ArgumentOutOfRangeException이 발생하므로 주의해야 합니다.

예제 1: 단일 항목 제거하기

다음은 OrderedDictionary에서 인덱스 4에 해당하는 항목을 제거하는 예제입니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("A", "Books");
      dict.Add("B", "Electronics");
      dict.Add("C", "Smart Wearables");
      dict.Add("D", "Pet Supplies");
      dict.Add("E", "Clothing");
      dict.Add("F", "Footwear");

      Console.WriteLine("OrderedDictionary 요소...");
      foreach(DictionaryEntry d in dict) {
         Console.WriteLine(d.Key + " " + d.Value);
      }

      Console.WriteLine("OrderedDictionary의 요소 수 = " + dict.Count);

      dict.RemoveAt(4);

      Console.WriteLine("OrderedDictionary의 요소 수(업데이트 후) = " + dict.Count);
   }
}

출력 결과

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

OrderedDictionary 요소...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
OrderedDictionary의 요소 수 = 6
OrderedDictionary의 요소 수(업데이트 후) = 5

인덱스는 0부터 시작하므로 RemoveAt(4)를 호출하면 다섯 번째 항목인 E Clothing이 제거되고, 전체 요소 수가 6에서 5로 줄어듭니다.

예제 2: 여러 항목 연속으로 제거하기

이번에는 RemoveAt() 메서드를 연속으로 호출하여 두 개의 항목을 제거하는 예제를 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("1", "AB");
      dict.Add("2", "CD");
      dict.Add("3", "MN");
      dict.Add("4", "PQ");

      Console.WriteLine("OrderedDictionary 요소...");
      foreach(DictionaryEntry d in dict) {
         Console.WriteLine(d.Key + " " + d.Value);
      }

      Console.WriteLine("OrderedDictionary의 요소 수 = " + dict.Count);

      dict.RemoveAt(1);
      dict.RemoveAt(2);

      Console.WriteLine("OrderedDictionary의 요소 수(업데이트 후) = " + dict.Count);
   }
}

출력 결과

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

OrderedDictionary 요소...
1 AB
2 CD
3 MN
4 PQ
OrderedDictionary의 요소 수 = 4
OrderedDictionary의 요소 수(업데이트 후) = 2

첫 번째 RemoveAt(1) 호출로 2 CD가 제거되면 나머지 항목이 앞으로 이동하여 [1 AB, 3 MN, 4 PQ] 상태가 됩니다. 이후 두 번째 RemoveAt(2) 호출로 4 PQ가 제거되어 최종적으로 2개의 항목만 남게 됩니다.

정리 및 참고 사항

  • OrderedDictionary의 인덱스는 0부터 시작합니다.
  • RemoveAt(index)를 호출하면 해당 위치의 항목이 삭제되고, 뒤쪽 항목들이 자동으로 앞으로 이동합니다.
  • 항목이 제거될 때마다 Count 속성 값이 1씩 감소합니다.
  • 컬렉션의 크기보다 크거나 음수인 인덱스를 전달하면 ArgumentOutOfRangeException 예외가 발생합니다.