Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

Collection 요소를 C#의 배열에 복사

<시간/>

Collection 요소를 배열에 복사하기 위한 코드는 다음과 같습니다 -

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("\nArray...");
      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

이제 다른 예를 살펴보겠습니다 -

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("\nArray...");
      foreach(string str in strArr){
         Console.WriteLine(str);
      }
   }
}

출력

이것은 다음과 같은 출력을 생성합니다 -

Collection....
One
Two
Three
Four
Five

Array...

One
Two
Three
Four
Five