List เป็น Generic Collection เก็บข้อมูลชนิดเดียวกัน ใช้ CopyTo เพื่อ Clone
ประกาศ List และเพิ่มข้อมูล:
List<string> myList = new List<string>();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database");
สร้างอาร์เรย์ใหม่และ Copy:
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