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

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

C#에서 OrderedDictionary의 요소들을 지정된 인덱스부터 시작하는 배열(Array) 인스턴스에 복사하려면 CopyTo() 메서드를 사용합니다. 이 메서드는 사전의 모든 요소를 지정한 위치부터 배열에 순서대로 복사합니다.

OrderedDictionary.CopyTo() 메서드란?

CopyTo() 메서드는 OrderedDictionary 컬렉션의 각 키-값 쌍을 DictionaryEntry 구조체 형태로 대상 배열에 복사합니다. 복사는 두 번째 매개변수로 전달된 인덱스 위치에서 시작됩니다.

예제 1: 문자열 값을 가진 OrderedDictionary 복사하기

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

public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add(1, "Harry");
      dict.Add(2, "Mark");
      dict.Add(3, "John");
      dict.Add(4, "Jacob");
      dict.Add(5, "Tim");

      Console.WriteLine("OrderedDictionary 요소...");
      foreach(DictionaryEntry d in dict){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      // 사전 개수만큼 크기를 가진 배열 생성
      DictionaryEntry[] dictArr = new DictionaryEntry[dict.Count];

      Console.WriteLine("\n배열로 복사 중...");
      dict.CopyTo(dictArr, 0);

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

실행 결과

위 코드를 실행하면 다음과 같은 출력이 나타납니다.

OrderedDictionary 요소...
1 Harry
2 Mark
3 John
4 Jacob
5 Tim
배열로 복사 중...
Key = 5, Value = Tim
Key = 4, Value = Jacob
Key = 3, Value = John
Key = 2, Value = Mark
Key = 1, Value = Harry

예제 2: 배열 크기가 더 큰 경우

대상 배열의 크기가 사전의 요소 수보다 클 경우, 남은 공간은 기본값으로 채워집니다. 아래 예제에서 확인해 보겠습니다.

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

public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add(1, 10);
      dict.Add(2, 20);

      Console.WriteLine("OrderedDictionary 요소...");
      foreach(DictionaryEntry d in dict){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      // 요소가 2개뿐이지만 배열 크기는 5로 설정
      DictionaryEntry[] dictArr = new DictionaryEntry[5];

      Console.WriteLine("\n배열로 복사 중...");
      dict.CopyTo(dictArr, 0);

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

실행 결과

위 코드를 실행하면 다음과 같은 출력이 나타납니다.

OrderedDictionary 요소...
1 10
2 20
배열로 복사 중...
Key = 2, Value = 20
Key = 1, Value = 10
Key = , Value =
Key = , Value =
Key = , Value =

정리 및 주요 포인트

위 예제들에서 알 수 있듯이, CopyTo() 메서드 사용 시 다음 사항을 유의해야 합니다.

  • 복사된 요소들은 삽입 순서와 반대 순서로 배열에 저장될 수 있습니다.
  • 대상 배열의 크기가 사전 요소 수보다 작으면 ArgumentException이 발생할 수 있습니다.
  • 배열이 더 클 경우 나머지 요소는 DictionaryEntry의 기본값(Key와 Value가 모두 null)으로 남습니다.
  • 시작 인덱스를 조정하면 원하는 위치부터 복사할 수 있습니다.