Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sao chép phần tử Collection sang mảng trong C#

Để sao chép các phần tử của Collection<T> sang mảng, ta dùng phương thức CopyTo. Dưới đây là các ví dụ.

Ví dụ 1

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);
        }
    }
}

Kết quả

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

Ví dụ 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");
        
        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);
        }
    }
}

Kết quả

Collection....
One
Two
Three
Four
Five
Array...
One
Two
Three
Four
Five