如何複製或克隆 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);
      }
   }
}

更新於:2020 年 6 月 21 日

3 萬多觀看

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告