C#에서 Hashtable의 요소를 배열(Array) 인스턴스로 복사하려면 CopyTo() 메서드를 사용합니다. 이 메서드는 Hashtable에 저장된 키-값 쌍을 DictionaryEntry 구조체 배열로 손쉽게 복사해 줍니다.
CopyTo() 메서드의 구조
Hashtable.CopyTo(Array array, int arrayIndex)는 두 개의 매개변수를 받습니다.
- array: Hashtable의 요소가 복사될 대상 배열
- arrayIndex: 복사가 시작될 배열 내 위치(인덱스)
예제 1: 배열 처음부터 전체 복사하기
다음 예제에서는 Hashtable의 모든 요소를 DictionaryEntry 배열의 인덱스 0부터 복사합니다.
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");
Console.WriteLine("Hashtable 키와 값 쌍...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1}", entry.Key, entry.Value);
}
Console.WriteLine("배열 인스턴스로 복사...");
DictionaryEntry[] dictArr = new DictionaryEntry[hash.Count];
hash.CopyTo(dictArr, 0);
for (int i = 0; i < dictArr.Length; i++)
Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
}
출력 결과
Hashtable 키와 값 쌍...
1 and AB
2 and CD
3 and EF
4 and GH
5 and IJ
배열 인스턴스로 복사...
Key = 1, Value = AB
Key = 2, Value = CD
Key = 3, Value = EF
Key = 4, Value = GH
Key = 5, Value = IJ
코드 설명
위 예제에서는 hash.Count를 사용해 Hashtable과 동일한 크기의 배열을 생성한 뒤, CopyTo(dictArr, 0)을 호출하여 인덱스 0부터 모든 요소를 복사했습니다. 배열 크기가 Hashtable의 요소 수와 정확히 일치하기 때문에 모든 키-값 쌍이 빠짐없이 저장됩니다.
예제 2: 특정 인덱스부터 복사하기
이번에는 배열의 중간 위치인 인덱스 2부터 복사하는 예제입니다. 이 경우 복사되지 않은 나머지 영역은 기본값으로 남게 됩니다.
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable(5);
hash.Add("1", "AB");
hash.Add("2", "CD");
Console.WriteLine("Hashtable 키와 값 쌍...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} and {1}", entry.Key, entry.Value);
}
Console.WriteLine("배열 인스턴스로 복사...");
DictionaryEntry[] dictArr = new DictionaryEntry[5];
hash.CopyTo(dictArr, 2);
for (int i = 0; i < dictArr.Length; i++)
Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
}
출력 결과
Hashtable 키와 값 쌍...
1 and AB
2 and CD
배열 인스턴스로 복사...
Key = , Value =
Key = , Value =
Key = 1, Value = AB
Key = 2, Value = CD
Key = , Value =
결과 분석
두 번째 예제에서는 배열 크기를 5로 지정하고 인덱스 2부터 복사했습니다. 그 결과는 다음과 같습니다.
- 인덱스 0과 1은 복사 대상이 아니므로
DictionaryEntry의 기본값(Key와 Value가 null)이 출력됩니다. - 인덱스 2와 3에 Hashtable의 두 요소가 순서대로 복사됩니다.
- 인덱스 4 역시 복사되지 않아 기본값이 그대로 출력됩니다.
사용 시 주의 사항
- 대상 배열의 크기는 최소
arrayIndex + Hashtable.Count이상이어야 하며, 그렇지 않으면ArgumentException이 발생합니다. - Hashtable은 정렬되지 않은(unordered) 컬렉션이므로 복사되는 요소의 순서는 보장되지 않습니다.
- 복사된 각 요소는
DictionaryEntry구조체이므로, 값을 읽을 때는.Key와.Value속성을 사용해야 합니다.