รายการคือคอลเล็กชันทั่วไปเพื่อเก็บองค์ประกอบของประเภทข้อมูลเดียวกัน
หากต้องการโคลนรายการ คุณสามารถใช้วิธี CopyTo ได้
ประกาศรายการและเพิ่มองค์ประกอบ -
List < string > myList = new List < string > ();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database"); ตอนนี้สร้างอาร์เรย์ใหม่และโคลนรายการลงในนั้น -
string[] arr = new string[10]; myList.CopyTo(arr);
นี่คือรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
List < string > myList = new List < string > ();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database");
Console.WriteLine("First list...");
foreach(string value in myList) {
Console.WriteLine(value);
}
string[] arr = new string[10];
myList.CopyTo(arr);
Console.WriteLine("After cloning...");
foreach(string value in arr) {
Console.WriteLine(value);
}
}
} ผลลัพธ์
First list... Programming Web Dev Database After cloning... Programming Web Dev Database