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

C#에서 Collection 요소를 배열로 복사하는 방법

C#에서 Collection<T>의 요소를 배열로 복사하려면 CopyTo() 메서드를 사용합니다. 이 메서드는 컬렉션의 모든 요소를 지정한 인덱스 위치부터 시작하여 대상 배열에 순서대로 복사합니다.

CopyTo() 메서드의 매개변수

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

  • array – 컬렉션 요소가 복사될 대상 1차원 배열
  • index – 복사가 시작되는 대상 배열의 인덱스 (0부터 시작)

단, 대상 배열의 크기는 (시작 인덱스 + 컬렉션 요소 수) 이상이어야 하며, 그렇지 않으면 예외가 발생합니다.

예제 1

다음은 Collection의 요소를 배열의 인덱스 2부터 복사하는 코드입니다 −

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<string> col = new Collection<string>();
      col.Add("One");
      col.Add("Two");
      col.Add("Three");
      col.Add("Four");
      col.Add("Five");
      col.Add("Six");
      col.Add("Seven");
      col.Add("Eight");
      Console.WriteLine("Collection....");
      foreach(string str in col){
         Console.WriteLine(str);
      }
      string[] strArr = new string[10];
      col.CopyTo(strArr, 2);
      Console.WriteLine("
Array...");
      foreach(string str in strArr){
         Console.WriteLine(str);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다 −

Collection....
One
Two
Three
Four
Five
Six
Seven
Eight

Array...

One
Two
Three
Four
Five
Six
Seven
Eight

배열의 크기가 10이고 인덱스 2부터 복사했기 때문에, 배열의 앞쪽 두 위치(인덱스 0과 1)는 비어 있는 상태(null)로 남고, 그 뒤부터 컬렉션의 요소들이 순서대로 채워집니다. 따라서 출력 시 빈 줄이 먼저 표시되는 것을 확인할 수 있습니다.

예제 2

이번에는 시작 인덱스를 3으로 지정한 또 다른 예제를 살펴보겠습니다 −

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<string> col = new Collection<string>();
      col.Add("One");
      col.Add("Two");
      col.Add("Three");
      col.Add("Four");
      col.Add("Five");
      Console.WriteLine("Collection....");
      foreach(string str in col){
         Console.WriteLine(str);
      }
      string[] strArr = new string[10];
      col.CopyTo(strArr, 3);
      Console.WriteLine("
Array...");
      foreach(string str in strArr){
         Console.WriteLine(str);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다 −

Collection....
One
Two
Three
Four
Five

Array...

One
Two
Three
Four
Five

이처럼 CopyTo() 메서드를 활용하면 원하는 시작 위치를 지정하여 Collection의 요소를 손쉽게 배열로 복사할 수 있습니다. 컬렉션 데이터를 배열 기반 API와 연동하거나 특정 오프셋에 데이터를 배치해야 할 때 유용하게 사용됩니다.