Để sao chép hoặc nhân bản một danh sách C #, trước tiên hãy đặt một danh sách.
List < string > myList = new List < string > ();
myList.Add("One");
myList.Add("Two"); Bây giờ hãy 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[10]; myList.CopyTo(arr);
Hãy cho chúng tôi xem mã hoàn chỉnh để sao chép danh sách vào mảng một chiều.
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List < string > myList = new List < string > ();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four");
Console.WriteLine("First list...");
foreach(string value in list1) {
Console.WriteLine(value);
}
string[] arr = new string[20];
myList.CopyTo(arr);
Console.WriteLine("After copy...");
foreach(string value in arr) {
Console.WriteLine(value);
}
}
}