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

C#에서 ArrayList 전체를 1차원 배열로 복사하는 방법

C#에서 ArrayList의 모든 요소를 1차원 배열에 복사하려면 CopyTo() 메서드를 사용합니다. CopyTo()는 ArrayList의 요소를 지정한 배열에 순서대로 복사하며, 대상 배열은 복사할 요소 수를 담을 수 있을 만큼 충분한 크기여야 합니다.

예제 1: 문자열 배열로 복사하기

다음 예제에서는 문자열 요소를 가진 ArrayList를 String 배열에 복사합니다.

using System;
using System.Collections;

public class Demo {
   public static void Main() {
      ArrayList list = new ArrayList();
      list.Add("AB");
      list.Add("BC");
      list.Add("CD");
      list.Add("EF");
      list.Add("GH");
      list.Add("IJ");
      list.Add("KL");
      list.Add("MN");

      String[] strArr = new String[10];

      Console.WriteLine("ArrayList...");
      foreach(Object obj in list)
         Console.WriteLine("{0}", obj);

      list.CopyTo(strArr);

      Console.WriteLine("\nArrayList에서 복사한 후의 문자열 배열...");
      foreach(Object ob in strArr)
         Console.WriteLine("{0}", ob);
   }
}

출력 결과

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

ArrayList...
AB
BC
CD
EF
GH
IJ
KL
MN
ArrayList에서 복사한 후의 문자열 배열...
AB
BC
CD
EF
GH
IJ
KL
MN

배열 크기를 10으로 선언했지만 ArrayList에는 8개의 요소만 있으므로, 나머지 2개 위치는 기본값인 null로 유지됩니다.

예제 2: 정수 배열로 복사하기

이번에는 정수 요소를 가진 ArrayList를 int 배열에 복사해 보겠습니다.

using System;
using System.Collections;

public class Demo {
   public static void Main() {
      ArrayList list = new ArrayList();
      list.Add(100);
      list.Add(200);
      list.Add(300);
      list.Add(400);
      list.Add(500);
      list.Add(600);
      list.Add(700);
      list.Add(800);
      list.Add(900);
      list.Add(1000);

      int[] intArr = new int[10];

      Console.WriteLine("ArrayList...");
      foreach(Object obj in list)
         Console.WriteLine("{0}", obj);

      list.CopyTo(intArr);

      Console.WriteLine("\nArrayList에서 복사한 후의 정수 배열...");
      foreach(Object ob in intArr)
         Console.WriteLine("{0}", ob);
   }
}

출력 결과

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

ArrayList...
100
200
300
400
500
600
700
800
900
1000

ArrayList에서 복사한 후의 정수 배열...
100
200
300
400
500
600
700
800
900
1000

참고 사항

CopyTo() 메서드는 세 가지 오버로드를 제공합니다.

  • CopyTo(Array) − 전체 ArrayList를 배열의 시작 위치부터 복사합니다.
  • CopyTo(Array, Int32) − 전체 ArrayList를 배열의 지정한 인덱스 위치부터 복사합니다.
  • CopyTo(Int32, Array, Int32, Int32) − ArrayList의 특정 범위를 배열의 지정한 위치부터 복사합니다.

또한 대상 배열이 null이거나, 배열의 크기가 복사할 요소 수보다 작으면 ArgumentException 또는 ArgumentOutOfRangeException이 발생할 수 있으므로 주의해야 합니다.