C#에서 Hashtable 클래스에 저장된 요소의 개수를 확인하려면 Count 속성을 사용하면 됩니다. 이 속성은 컬렉션에 실제로 포함된 키-값 쌍의 총 개수를 정수(int) 형태로 반환합니다.
Hashtable에 요소 추가하기
먼저 Hashtable 객체를 생성하고 Add() 메서드를 사용해 여러 요소를 추가해 보겠습니다.
Hashtable ht = new Hashtable();
ht.Add("One", "Tom");
ht.Add("Two", "Jack");
ht.Add("Three", "Peter");
ht.Add("Four", "Russel");
ht.Add("Five", "Brad");
ht.Add("Six", "Bradley");
ht.Add("Seven", "Steve");
ht.Add("Eight", "David");위 코드는 "One"부터 "Eight"까지 8개의 키와 각각 대응되는 값을 저장합니다.
Count 속성으로 요소 개수 세기
Hashtable에 저장된 요소의 개수를 확인하는 방법은 매우 간단합니다. 다음과 같이 Count 속성을 호출하기만 하면 됩니다.
ht.Count
전체 예제 코드
아래는 C#에서 Hashtable의 Count 속성을 사용하는 방법을 보여주는 완전한 예제입니다.
예제
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
Hashtable ht = new Hashtable();
ht.Add("One", "Tom");
ht.Add("Two", "Jack");
ht.Add("Three", "Peter");
ht.Add("Four", "Russel");
ht.Add("Five", "Brad");
ht.Add("Six", "Bradley");
ht.Add("Seven", "Steve");
ht.Add("Eight", "David");
Console.WriteLine("Count = " + ht.Count);
Console.ReadKey();
}
}
}실행 결과
Count = 8
정리
Count 속성은 Hashtable뿐만 아니라 ArrayList, Queue, Stack 등 System.Collections 네임스페이스의 대부분의 컬렉션 클래스에서 동일하게 제공됩니다. 참고로 최신 C# 프로젝트에서는 형식 안정성이 뛰어난 Dictionary<TKey, TValue> 제네릭 클래스를 사용하는 것이 권장되지만, 기존 코드를 유지보수하거나 레거시 시스템을 다룰 때는 여전히 Hashtable이 자주 등장하므로 Count 속성의 사용법을 숙지해 두는 것이 좋습니다.