如何複製或克隆 C# 列表?
若要複製或克隆一個 C# 列表,首先設定一個列表 −
List < string > list1 = new List < string > (); list1.Add("One"); list1.Add("Two"); list1.Add("Three"); list1.Add("Four");
現在宣告一個字串陣列,並使用 CopyTo() 方法進行復制。
string[] arr = new string[20]; list1.CopyTo(arr);
我們來看一下將列表複製到一維陣列的完整程式碼。
示例
using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main() { List < string > list1 = new List < string > (); list1.Add("One"); list1.Add("Two"); list1.Add("Three"); list1.Add("Four"); 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); } } }
廣告