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

C#에서 HybridDictionary 항목을 배열 인스턴스로 복사하는 방법

개요

HybridDictionary는 저장된 요소 수가 적을 때는 ListDictionary처럼 동작하고, 요소 수가 많아지면 자동으로 Hashtable로 전환되는 특수한 컬렉션 클래스입니다. 이 컬렉션에 담긴 키-값 쌍은 CopyTo() 메서드를 사용하여 DictionaryEntry 타입의 배열 인스턴스로 손쉽게 복사할 수 있습니다.

CopyTo() 메서드는 두 개의 매개변수를 받습니다.

  • 첫 번째 매개변수: 복사 대상이 되는 1차원 Array 객체
  • 두 번째 매개변수: 복사가 시작될 배열의 인덱스(0부터 시작)

그럼 실제 예제를 통해 살펴보겠습니다.

예제 1

아래 코드는 HybridDictionary의 항목을 배열 인스턴스로 복사하는 기본적인 방법을 보여줍니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      HybridDictionary dict = new HybridDictionary();
      dict.Add("1", "SUV");
      dict.Add("2", "AUV");
      dict.Add("3", "Utility Vehicle");
      dict.Add("4", "MUV");
      dict.Add("5", "Compact Car");
      dict.Add("6", "Convertible");
      Console.WriteLine("HybridDictionary Key and Value pairs...");
      foreach(DictionaryEntry entry in dict){
         Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
      }
      DictionaryEntry[] dictArr = new DictionaryEntry[10];
      Console.WriteLine("\nCopied to Array Instance...");
      dict.CopyTo(dictArr, 2);
      for (int i = 0; i < dictArr.Length; i++)
         Console.WriteLine("Key = "+dictArr[i].Key + ", Value = " + dictArr[i].Value);
  }
}

출력 결과

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

HybridDictionary Key and Value pairs... 1 and SUV
2 and AUV
3 and Utility Vehicle
4 and MUV
5 and Compact Car
6 and Convertible

Copied to Array Instance...
Key = , Value =
Key = , Value =
Key = 1, Value = SUV
Key = 2, Value = AUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = MUV
Key = 5, Value = Compact Car
Key = 6, Value = Convertible
Key = , Value =
Key = , Value =

출력 결과를 보면 복사 시작 인덱스를 2로 지정했기 때문에 배열의 앞 두 칸(인덱스 0, 1)은 비어 있고, 인덱스 2부터 항목들이 순서대로 채워진 것을 확인할 수 있습니다.

예제 2

이번에는 생성자에 초기 용량을 지정하고, 복사 시작 인덱스를 0으로 설정한 또 다른 예제입니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      HybridDictionary dict = new HybridDictionary(10);
      dict.Add("1", "SUV");
      dict.Add("2", "AUV");
      dict.Add("3", "Utility Vehicle");
      dict.Add("4", "MUV");
      Console.WriteLine("HybridDictionary Key and Value pairs...");
      foreach(DictionaryEntry entry in dict){
         Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
      }
      DictionaryEntry[] dictArr = new DictionaryEntry[10];
      Console.WriteLine("\nCopied to Array Instance...");
      dict.CopyTo(dictArr, 0);
      for (int i = 0; i < dictArr.Length; i++)
         Console.WriteLine("Key = "+dictArr[i].Key + ", Value = " + dictArr[i].Value);
  }
}

출력 결과

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

HybridDictionary Key and Value pairs... 1 and SUV
2 and AUV
3 and Utility Vehicle
4 and MUV

Copied to Array Instance...
Key = 1, Value = SUV
Key = 2, Value = AUV
Key = 3, Value = Utility Vehicle
Key = 4, Value = MUV
Key = , Value =
Key = , Value =
Key = , Value =
Key = , Value =
Key = , Value =
Key = , Value =

정리

HybridDictionary의 CopyTo() 메서드를 사용하면 컬렉션의 모든 키-값 쌍을 DictionaryEntry 배열로 한 번에 복사할 수 있습니다. 이때 주의할 점은 다음과 같습니다.

  • 대상 배열의 크기는 복사 시작 인덱스 + 컬렉션 요소 수보다 크거나 같아야 합니다.
  • 복사 시작 인덱스가 0보다 작거나 배열 범위를 벗어나면 예외가 발생합니다.
  • 복사되지 않은 나머지 배열 요소는 DictionaryEntry 구조체의 기본값(Key와 Value가 null)으로 유지됩니다.