HybridDictionary는 System.Collections.Specialized 네임스페이스에 포함된 특수 컬렉션입니다. 저장된 요소가 적을 때는 ListDictionary처럼 동작하고, 요소가 많아지면 내부적으로 해시 테이블 방식으로 전환되어 성능을 최적화합니다.
HybridDictionary에 저장된 키/값 쌍의 개수를 확인할 때는 Count 속성을 사용합니다. 아래 예제를 통해 직접 확인해 보겠습니다.
예제 1: 두 개의 HybridDictionary 다루기
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
HybridDictionary dict1 = new HybridDictionary();
dict1.Add("A", "SUV");
dict1.Add("B", "MUV");
dict1.Add("C", "AUV");
Console.WriteLine("HybridDictionary1 요소 출력...");
foreach(DictionaryEntry d in dict1) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("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();
Console.WriteLine("HybridDictionary2 요소 출력...");
foreach(DictionaryEntry d in dict2) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Dictionary2의 키/값 쌍 개수 = " + dict2.Count);
dict2.Clear();
Console.WriteLine("Clear() 호출 후 Dictionary2의 키/값 쌍 개수 = " + dict2.Count);
}
}
실행 결과
HybridDictionary1 요소 출력... A SUV B MUV C AUV Dictionary1의 키/값 쌍 개수 = 3 HybridDictionary2 요소 출력... 1 One 2 Two 3 Three 4 Four 5 Five 6 Six Dictionary2의 키/값 쌍 개수 = 6 Clear() 호출 후 Dictionary2의 키/값 쌍 개수 = 0
첫 번째 딕셔너리에는 3개의 키/값 쌍이 저장되어 있으므로 Count 속성은 3을 반환합니다. 두 번째 딕셔너리에는 6개의 쌍이 있으므로 6이 출력됩니다. 이후 Clear() 메서드로 모든 요소를 제거하면 Count 값이 0으로 변경되는 것을 확인할 수 있습니다.
예제 2: 요소 추가 후 개수 변화 확인
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
HybridDictionary dict = new HybridDictionary();
dict.Add("A", "SUV");
dict.Add("B", "MUV");
dict.Add("C", "AUV");
Console.WriteLine("HybridDictionary 요소 출력...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("현재 키/값 쌍 개수 = " + dict.Count);
dict.Add("D", "Utility Vehicle");
dict.Add("E", "Convertible");
Console.WriteLine("요소 추가 후 키/값 쌍 개수 = " + dict.Count);
}
}
실행 결과
HybridDictionary 요소 출력... A SUV B MUV C AUV 현재 키/값 쌍 개수 = 3 요소 추가 후 키/값 쌍 개수 = 5
초기에는 3개의 키/값 쌍이 있었지만, Add() 메서드로 두 개의 항목을 추가한 뒤 Count 속성은 5를 반환합니다. 이처럼 Count 속성은 HybridDictionary에 현재 저장된 키/값 쌍의 개수를 실시간으로 반영하며, 요소의 추가나 삭제에 따라 그 값이 즉시 갱신됩니다.