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

C# HybridDictionary에서 특정 키 존재 여부 확인하기 (Contains 메서드)

C#의 HybridDictionary에 특정 키가 존재하는지 확인하려면 Contains() 메서드를 사용합니다. 이 메서드는 해당 키가 컬렉션에 있으면 true, 없으면 false를 반환하므로 키 검증 로직을 간결하게 작성할 수 있습니다.

HybridDictionary란?

HybridDictionarySystem.Collections.Specialized 네임스페이스에 정의된 특수 컬렉션입니다. 저장된 요소 수가 적을 때는 내부적으로 ListDictionary처럼 동작하고, 요소 수가 늘어나면 Hashtable로 자동 전환되기 때문에 소규모·대규모 데이터 모두에서 효율적인 성능을 발휘합니다.

예제 1 – Contains()로 키 확인하기

다음 예제에서는 다섯 개의 키-값 쌍을 담은 HybridDictionary를 만든 뒤, "C"라는 키가 존재하는지 확인해 봅니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      HybridDictionary dict = new HybridDictionary(5);
      dict.Add("A", "AB");
      dict.Add("B", "BC");
      dict.Add("C", "DE");
      dict.Add("D", "FG");
      dict.Add("E", "HI");
      Console.WriteLine("Key/Value pairs...");
      foreach(DictionaryEntry d in dict)
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      Console.WriteLine("Does HybridDictionary contains the key C? = "+dict.Contains("C"));
   }
}

이 코드를 실행하면 아래와 같은 결과가 출력됩니다.

Key/Value pairs...
Key = A, Value = AB
Key = B, Value = BC
Key = C, Value = DE
Key = D, Value = FG
Key = E, Value = HI
Does HybridDictionary contains the key C? = True

"C" 키가 실제로 존재하기 때문에 dict.Contains("C")True를 반환했습니다.

예제 2 – 존재하지 않는 키 확인 및 Clear() 활용

이번에는 두 개의 HybridDictionary를 생성하고, 존재하지 않는 키를 조회했을 때의 동작과 더불어 Clear() 메서드로 모든 요소를 삭제하는 과정까지 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      HybridDictionary dict1 = new HybridDictionary();
      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("HybridDictionary1 elements...");
      foreach(DictionaryEntry d in dict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Count of Key/value pairs in Dictionary1 = "+dict1.Count);

      HybridDictionary dict2 = new HybridDictionary();
      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("\nHybridDictionary2 elements...");
      foreach(DictionaryEntry d in dict2){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Count of Key/value pairs in Dictionary2 = "+dict2.Count);
      Console.WriteLine("Does HybridDictionary2 contains the key 10? = "+dict2.Contains(10));
      dict2.Clear();
      Console.WriteLine("Count of Key/value pairs in Dictionary2 (Updated) = "+dict2.Count);
   }
}

실행 결과는 다음과 같습니다.

HybridDictionary1 elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Count of Key/value pairs in Dictionary1 = 6

HybridDictionary2 elements...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
Count of Key/value pairs in Dictionary2 = 6
Does HybridDictionary2 contains the key 10? = False
Count of Key/value pairs in Dictionary2 (Updated) = 0

핵심 정리

  • Contains(object key)는 지정한 키가 HybridDictionary에 존재하면 true, 없으면 false를 반환합니다.
  • 존재하지 않는 키(위 예제의 정수 10 등)를 조회해도 예외가 발생하지 않고 false가 반환됩니다.
  • Clear() 메서드를 호출하면 모든 키-값 쌍이 삭제되어 Count 값이 0이 됩니다.
  • 초기 생성 시 용량을 지정(new HybridDictionary(5))하면 요소 추가 시 발생하는 재할당을 줄여 성능을 최적화할 수 있습니다.