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

C# Hashtable에 특정 키가 포함되어 있는지 확인하는 방법

C#에서 Hashtable에 특정 키가 존재하는지 확인하려면 Contains() 메서드를 사용합니다. 이 메서드는 지정한 키가 Hashtable에 있으면 true, 없으면 false를 반환합니다.

예제 1

다음은 Hashtable에 특정 키가 포함되어 있는지 확인하는 전체 코드입니다.

using System;
using System.Collections;

public class Demo {
   public static void Main(){
      Hashtable hash = new Hashtable();
      hash.Add("One", "Katie");
      hash.Add("Two", "John");
      hash.Add("Three", "Barry");
      hash.Add("Four", "");
      hash.Add("Five", "Harry");
      hash.Add("Six", "F");
      hash.Add("Seven", "Tom");
      hash.Add("Eight", "Andy");
      hash.Add("Nine", "I");
      hash.Add("Ten", "Tim");

      Console.WriteLine("Hashtable 키와 값 쌍 출력...");
      foreach(DictionaryEntry entry in hash){
         Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
      }

      Console.WriteLine("Hashtable이 고정 크기인가? = " + hash.IsFixedSize);
      Console.WriteLine("Hashtable이 읽기 전용인가? = " + hash.IsReadOnly);

      Hashtable hash2 = Hashtable.Synchronized(hash);
      Console.WriteLine("Hashtable이 동기화되어 있는가? = " + hash2.IsSynchronized);
      Console.WriteLine("Hashtable에 'Ten' 키가 포함되어 있는가? = " + hash.Contains("Ten"));
   }
}

출력 결과

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

Hashtable 키와 값 쌍 출력...
One and Katie
Ten and Tim
Five and Harry
Three and Barry
Seven and Tom
Two and John
Four and
Eight and Andy
Nine and I
Six and F
Hashtable이 고정 크기인가? = False
Hashtable이 읽기 전용인가? = False
Hashtable이 동기화되어 있는가? = True
Hashtable에 'Ten' 키가 포함되어 있는가? = True

예제 2

이번에는 다른 예제를 살펴보겠습니다. 숫자 문자열을 키로 사용하여 특정 키의 존재 여부를 확인하는 코드입니다.

using System;
using System.Collections;

public class Demo {
   public static void Main(){
      Hashtable hash = new Hashtable();
      hash.Add("1", "AB");
      hash.Add("2", "BC");
      hash.Add("3", "DE");
      hash.Add("4", "EF");
      hash.Add("5", "GH");
      hash.Add("6", "IJ");
      hash.Add("7", "KL");
      hash.Add("8", "MN");
      hash.Add("9", "OP");
      hash.Add("10", "QR");

      Console.WriteLine("키 3의 값 = " + hash["3"]);
      Console.WriteLine("Hashtable에 '12' 키가 포함되어 있는가? = " + hash.Contains("12"));
   }
}

출력 결과

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

키 3의 값 = DE
Hashtable에 '12' 키가 포함되어 있는가? = False

참고 사항

Contains() 메서드 외에도 ContainsKey() 메서드를 사용할 수 있으며, 두 메서드는 동일하게 동작합니다. 반면 ContainsValue()는 키가 아닌 값의 존재 여부를 확인할 때 사용됩니다. 또한 Hashtable은 해시 기반 컬렉션이므로 요소의 저장 순서가 보장되지 않으며, 스레드 안전성이 필요한 경우 위 예제처럼 Hashtable.Synchronized()를 사용해 동기화된 래퍼를 생성할 수 있습니다.