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

C# Hashtable에서 키/값 쌍 개수 구하기 – Count 속성 활용 방법

C#에서 Hashtable에 저장된 키/값 쌍의 개수를 확인하려면 Count 속성을 사용하면 됩니다. 이 속성은 Hashtable에 현재 포함되어 있는 요소(키/값 쌍)의 총 개수를 정수 형태로 반환합니다.

아래 예제들을 통해 실제 사용 방법을 살펴보겠습니다.

예제 1: 기본적인 Count 속성 사용

먼저 Hashtable을 생성하고 요소를 추가한 뒤, 요소 추가 전후로 Count 값이 어떻게 변하는지 확인해 보겠습니다.

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable();
      hash.Add("A", "SUV");
      hash.Add("B", "MUV");
      hash.Add("C", "AUV");

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

      Console.WriteLine("키/값 쌍 개수 = " + hash.Count);

      hash.Add("D", "Utility Vehicle");
      hash.Add("E", "Convertible");

      Console.WriteLine("키/값 쌍 개수 (업데이트 후) = " + hash.Count);
   }
}

실행 결과

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

Hashtable 요소 출력...
C AUV
A SUV
B MUV
키/값 쌍 개수 = 3
키/값 쌍 개수 (업데이트 후) = 5

처음에는 3개의 키/값 쌍이 있었지만, Add() 메서드로 두 개의 요소를 더 추가한 후 개수가 5로 늘어난 것을 확인할 수 있습니다.

예제 2: 초기 용량 지정 및 열거자 활용

이번에는 생성자에서 초기 용량을 지정하여 Hashtable을 만들고, IDictionaryEnumerator를 사용해 모든 키/값 쌍을 순회하면서 개수를 확인하는 예제입니다.

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable(10);
      hash.Add("1", "A");
      hash.Add("2", "B");
      hash.Add("3", "C");
      hash.Add("4", "D");
      hash.Add("5", "E");
      hash.Add("6", "F");
      hash.Add("7", "G");
      hash.Add("8", "H");
      hash.Add("9", "I");
      hash.Add("10", "J");

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

      Console.WriteLine("\n열거자를 통해 Hashtable 순회...");
      IDictionaryEnumerator demoEnum = hash.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
   }
}

실행 결과

Hashtable 키와 값 쌍 출력...
10 and J
1 and A
2 and B
3 and C
4 and D
5 and E
6 and F
7 and G
8 and H
9 and I
Hashtable이 고정 크기인가요? = False
Hashtable의 키/값 쌍 개수 = 10

열거자를 통해 Hashtable 순회...
Key = 10, Value = J
Key = 1, Value = A
Key = 2, Value = B
Key = 3, Value = C
Key = 4, Value = D
Key = 5, Value = E
Key = 6, Value = F
Key = 7, Value = G
Key = 8, Value = H
Key = 9, Value = I

정리

  • Count 속성은 Hashtable에 포함된 키/값 쌍의 실제 개수를 반환합니다.
  • IsFixedSize 속성을 사용하면 Hashtable이 고정 크기인지 여부를 확인할 수 있습니다. 일반적인 Hashtable은 항상 False를 반환합니다.
  • foreach 문과 DictionaryEntry, 또는 IDictionaryEnumerator를 사용하여 Hashtable의 모든 요소를 순회할 수 있습니다.
  • Hashtable은 해시 코드 기반으로 요소를 저장하기 때문에 출력 순서는 삽입 순서와 다를 수 있다는 점에 유의해야 합니다.