Để sao chép một bộ sưu tập vào một mảng, trước tiên hãy đặt nó -
List < string > list1 = new List < string > ();
list1.Add("Car");
list1.Add("Bus");
list1.Add("Motorbike");
list1.Add("Train"); Bây giờ khai báo một mảng chuỗi và sử dụng phương thức CopyTo () để sao chép -
string[] arr = new string[20]; list1.CopyTo(arr);
Hãy cho chúng tôi xem mã hoàn chỉnh để sao chép bộ sưu tập vào mảng -
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List < string > list1 = new List < string > ();
list1.Add("Car");
list1.Add("Bus");
list1.Add("Motobike");
list1.Add("Train");
Console.WriteLine("First list...");
foreach(string value in list1) {
Console.WriteLine(value);
}
string[] arr = new string[20];
list1.CopyTo(arr);
Console.WriteLine("After copy...");
foreach(string value in arr) {
Console.WriteLine(value);
}
}
}