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

C# OrderedDictionary에서 지정된 키의 항목을 제거하는 방법

C#에서 OrderedDictionary에 저장된 항목 중 지정된 키와 일치하는 항목을 삭제하려면 Remove() 메서드를 사용하면 됩니다. 이 메서드는 매개변수로 전달된 키에 해당하는 항목을 컬렉션에서 제거하며, 해당 키가 존재하지 않으면 아무 작업도 수행하지 않고 오류 없이 그대로 통과합니다.

Remove() 메서드의 기본 문법

public void Remove(object key);

매개변수 key는 제거하고자 하는 항목의 키를 나타냅니다.

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

다음 예제에서는 여러 항목을 추가한 후, 키 "E"에 해당하는 항목 하나를 제거하는 과정을 보여줍니다.

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);

      // 키가 "E"인 항목 제거
      dict.Remove("E");

      Console.WriteLine("제거 후 OrderedDictionary의 요소 개수 = " + dict.Count);
   }
}

실행 결과

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

OrderedDictionary 요소 출력...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
OrderedDictionary의 요소 개수 = 6
제거 후 OrderedDictionary의 요소 개수 = 5

출력 결과를 보면 처음에는 6개였던 요소 개수가 Remove("E") 호출 이후 5개로 줄어든 것을 확인할 수 있습니다.

예제 2: 여러 항목 한 번에 제거하기

이번에는 두 개의 항목을 연속해서 제거하는 예제입니다.

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

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("A", "One");
      dict.Add("B", "Two");
      dict.Add("C", "Three");
      dict.Add("D", "Four");

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

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

      // 키가 "C"와 "D"인 항목 제거
      dict.Remove("C");
      dict.Remove("D");

      Console.WriteLine("제거 후 OrderedDictionary의 요소 개수 = " + dict.Count);
   }
}

실행 결과

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

OrderedDictionary 요소 출력...
A One
B Two
C Three
D Four
OrderedDictionary의 요소 개수 = 4
제거 후 OrderedDictionary의 요소 개수 = 2

정리

OrderedDictionary.Remove() 메서드는 삽입 순서를 유지하는 딕셔너리에서 특정 키의 항목을 손쉽게 삭제할 수 있는 방법입니다. 제거 후에는 Count 속성 값이 자동으로 갱신되므로, 별도의 처리 없이도 현재 저장된 항목 수를 정확하게 파악할 수 있습니다. 또한 존재하지 않는 키를 전달해도 예외가 발생하지 않기 때문에, 키의 존재 여부를 미리 검사하지 않아도 안전하게 사용할 수 있습니다.