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

C# ListDictionary에서 특정 키를 가진 항목 제거하는 방법

C#의 ListDictionary 컬렉션에서 지정된 키를 가진 항목을 제거하려면 Remove() 메서드를 사용하면 됩니다. 이 메서드는 매개변수로 전달된 키에 해당하는 키/값 쌍을 컬렉션에서 삭제하며, 해당 키가 존재하지 않으면 아무 작업도 수행하지 않습니다.

예제 1

두 개의 ListDictionary를 생성하고, 두 번째 딕셔너리에서 특정 키를 제거하는 예제입니다.

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

public class Demo {
   public static void Main(){
      ListDictionary dict1 = new ListDictionary();
      dict1.Add("A", "Books");
      dict1.Add("B", "Electronics");
      dict1.Add("C", "Smart Wearables");
      dict1.Add("D", "Pet Supplies");
      dict1.Add("E", "Clothing");
      dict1.Add("F", "Footwear");
      Console.WriteLine("ListDictionary1 요소...");
      foreach(DictionaryEntry d in dict1) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      ListDictionary dict2 = new ListDictionary();
      dict2.Add("1", "One");
      dict2.Add("2", "Two");
      dict2.Add("3", "Three");
      dict2.Add("4", "Four");
      dict2.Add("5", "Five");
      dict2.Add("6", "Six");
      Console.WriteLine("\nListDictionary2 요소...");
      foreach(DictionaryEntry d in dict2) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("딕셔너리 2의 키/값 쌍 개수 = "+dict2.Count);
      dict2.Remove("4");
      Console.WriteLine("딕셔너리 2의 키/값 쌍 개수 (업데이트 후) = "+dict2.Count);
   }
}

출력 결과

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

ListDictionary1 요소...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
ListDictionary2 요소...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
딕셔너리 2의 키/값 쌍 개수 = 6
딕셔너리 2의 키/값 쌍 개수 (업데이트 후) = 5

출력 결과를 보면 Remove("4") 호출 전에는 항목이 6개였지만, 키 "4"를 가진 항목이 제거된 후에는 5개로 줄어든 것을 확인할 수 있습니다.

예제 2

이번에는 여러 개의 항목을 연속해서 제거하는 예제를 살펴보겠습니다.

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

public class Demo {
   public static void Main() {
      ListDictionary dict = new ListDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");
      dict.Add("6", "Six");
      Console.WriteLine("ListDictionary 요소...");
      foreach(DictionaryEntry d in dict) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("딕셔너리의 키/값 쌍 개수 = "+dict.Count);
      dict.Remove("2");
      dict.Remove("3");
      dict.Remove("4");
      Console.WriteLine("딕셔너리의 키/값 쌍 개수 (업데이트 후) = "+dict.Count);
   }
}

출력 결과

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

ListDictionary 요소...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
딕셔너리의 키/값 쌍 개수 = 6
딕셔너리의 키/값 쌍 개수 (업데이트 후) = 3

정리

ListDictionary는 키/값 쌍이 적은 경우에 유용한 컬렉션으로, 내부적으로 단일 연결 리스트 방식으로 데이터를 저장합니다. Remove() 메서드를 사용하면 특정 키에 해당하는 항목을 손쉽게 삭제할 수 있으며, Count 속성을 통해 현재 저장된 키/값 쌍의 개수를 확인할 수 있습니다.