Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 StringDictionary를 지정된 인덱스의 배열로 복사하는 방법


C#에서 StringDictionary의 모든 요소를 1차원 배열의 지정된 인덱스 위치부터 복사하려면 CopyTo() 메서드를 사용합니다. 이 메서드는 두 가지 매개변수를 받습니다.

  • array : DictionaryEntry 요소를 복사할 대상 1차원 배열
  • index : 복사가 시작되는 배열의 인덱스(0부터 시작)

예제 1 – 인덱스 0부터 복사

아래 예제에서는 자동차 종류 10개가 담긴 StringDictionary를 생성한 뒤, DictionaryEntry 배열의 인덱스 0부터 전체를 복사합니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
public static void Main(){
StringDictionary strDict = new StringDictionary();
strDict.Add("1", "SUV");
strDict.Add("2", "AUV");
strDict.Add("3", "Electric Car");
strDict.Add("4", "Utility Vehicle");
strDict.Add("5", "Hatchback");
strDict.Add("6", "Compact car");
strDict.Add("7", "MUV");
strDict.Add("8", "Crossover");
strDict.Add("9", "Convertible");
strDict.Add("10", "Quadricycle");

DictionaryEntry[] arr = { new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry()};

strDict.CopyTo(arr, 0);

for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i].Key + " " + arr[i].Value);
}
}
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

10 Quadricycle
1 SUV
2 AUV
3 Electric Car
4 Utility Vehicle
5 Hatchback
6 Compact car
7 MUV
8 Crossover
9 Convertible

참고로 StringDictionary는 내부적으로 해시 테이블 기반으로 동작하기 때문에, 출력 순서가 입력 순서와 다르게 나타날 수 있습니다. 위 결과에서 "10 Quadricycle"이 가장 먼저 출력되는 것도 이러한 이유 때문입니다.

예제 2 – 인덱스 2부터 복사

이번에는 6개의 요소만 담긴 StringDictionary를 배열의 인덱스 2부터 복사해 보겠습니다. 이 경우 배열의 앞쪽 두 칸은 비어 있는 상태로 유지되고, 그 뒤부터 값이 채워집니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
public static void Main(){
StringDictionary strDict = new StringDictionary();
strDict.Add("1", "SUV");
strDict.Add("2", "AUV");
strDict.Add("3", "Electric Car");
strDict.Add("4", "Utility Vehicle");
strDict.Add("5", "Hatchback");
strDict.Add("6", "Compact car");

DictionaryEntry[] arr = { new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry(),
new DictionaryEntry()};

strDict.CopyTo(arr, 2);

for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i].Key + " " + arr[i].Value);
}
}
}

출력 결과

복사가 인덱스 2부터 시작되므로 배열의 처음 두 요소는 빈 DictionaryEntry로 남고, 그 이후 위치에 키-값 쌍이 순서대로 저장됩니다.

1 SUV
2 AUV
3 Electric Car
4 Utility Vehicle
5 Hatchback
6 Compact car

정리

CopyTo() 메서드를 활용하면 StringDictionary의 키-값 쌍을 DictionaryEntry 배열의 원하는 위치에 손쉽게 복사할 수 있습니다. 다만 대상 배열의 크기가 (시작 인덱스 + 딕셔너리 요소 수)보다 작으면 ArgumentException이 발생하므로, 배열 크기를 미리 충분히 확보해 두는 것이 안전합니다.