C#의 Hashtable에 저장된 모든 키를 담고 있는 ICollection을 가져오려면 Keys 속성을 사용하면 됩니다. 이 속성은 해시테이블 내부의 키 값들을 ICollection 형태로 반환하며, foreach 문을 활용해 각 키와 해당 값을 손쉽게 순회할 수 있습니다.
예제 1: 문자열 키를 사용하는 경우
다음은 문자열을 키로 사용하는 Hashtable에서 Keys 속성으로 ICollection을 가져오는 예제입니다.
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable hash = new Hashtable();
hash.Add("A", "Electronics");
hash.Add("B", "Appliances");
hash.Add("C", "Pet Supplies");
hash.Add("D", "Books");
hash.Add("E", "Toys");
hash.Add("F", "Footwear");
hash.Add("G", "Clothing");
ICollection col = hash.Keys;
foreach(string str in col)
Console.WriteLine(str + ": " + hash[str]);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
G: Clothing A: Electronics B: Appliances C: Pet Supplies D: Books E: Toys F: Footwear
예제 2: 정수형 키를 사용하는 경우
이번에는 정수(int) 타입을 키로 사용하는 Hashtable의 예제를 살펴보겠습니다. 동작 방식은 동일하며, Keys 속성이 반환한 컬렉션을 int 타입으로 순회합니다.
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable hash = new Hashtable();
hash.Add(1, "AB");
hash.Add(2, "CD");
hash.Add(3, "EF");
hash.Add(4, "GH");
hash.Add(5, "IJ");
hash.Add(6, "KL");
hash.Add(7, "MN");
ICollection col = hash.Keys;
foreach(int str in col)
Console.WriteLine("Key = " + str + ", Value = " + hash[str]);
}
}출력 결과
실행 결과는 다음과 같습니다.
Key = 7, Value = MN Key = 6, Value = KL Key = 5, Value = IJ Key = 4, Value = GH Key = 3, Value = EF Key = 2, Value = CD Key = 1, Value = AB
정리
Hashtable의 Keys 속성은 키만 모아둔 ICollection을 반환합니다. 참고로 해시테이블은 내부적으로 해시 기반 구조를 사용하기 때문에, 키가 추가된 순서와 무관하게 출력 순서가 달라질 수 있다는 점을 유의해야 합니다. 키와 값을 함께 다루어야 한다면 위 예제처럼 반환된 키를 인덱서(hash[key])에 전달하여 값을 조회하는 방식을 활용하면 됩니다.