C#의 HybridDictionary에서 키를 포함하는 ICollection을 가져오려면 Keys 속성을 사용하면 됩니다.
HybridDictionary는 요소 수가 적을 때는 ListDictionary처럼, 많아지면 Hashtable처럼 자동으로 전환되어 동작하는 특수한 사전 클래스입니다. Keys 속성은 저장된 모든 키를 담은 ICollection을 반환하며, CopyTo 메서드를 이용해 배열로 복사한 뒤 순회할 수 있습니다.
예제 1
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
HybridDictionary dict = new HybridDictionary();
dict.Add("One", "Katie");
dict.Add("Two", "Andy");
dict.Add("Three", "Gary");
dict.Add("Four", "Mark");
dict.Add("Five", "Marie");
dict.Add("Six", "Sam");
dict.Add("Seven", "Harry");
dict.Add("Eight", "Kevin");
dict.Add("Nine", "Ryan");
String[] strArr = new String[dict.Count];
dict.Keys.CopyTo(strArr, 0);
for (int i = 0; i < dict.Count; i++)
Console.WriteLine(strArr[i]);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Eight Seven Four Three One Five Six Two Nine
예제 2
이번에는 숫자 문자열을 키로 사용하는 또 다른 예제를 살펴보겠습니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
HybridDictionary dict = new HybridDictionary();
dict.Add("1", "A");
dict.Add("2", "B");
dict.Add("3", "C");
dict.Add("4", "D");
dict.Add("5", "E");
dict.Add("6", "F");
String[] strArr = new String[dict.Count];
dict.Keys.CopyTo(strArr, 0);
for (int i = 0; i < dict.Count; i++)
Console.WriteLine(strArr[i]);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
1 2 3 4 5 6
정리
HybridDictionary의 Keys 속성은 키 전체를 담은 ICollection을 제공합니다. 반환된 컬렉션은 CopyTo 메서드로 문자열 배열에 복사한 후 반복문을 통해 각 키를 순서대로 확인할 수 있으며, 이 방식은 값(Value)이 아닌 키만 필요할 때 유용하게 활용됩니다.