C#程式克隆或複製列表


要複製或克隆C#列表,首先設定一個列表。

List < string > myList = new List < string > ();
myList.Add("One");
myList.Add("Two");

現在宣告一個字串陣列並使用CopyTo()方法進行復制。

string[] arr = new string[10];
myList.CopyTo(arr);

讓我們看看將列表複製到一維陣列中的完整程式碼。

示例

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);
      }
   }
}

更新於: 22-Jun-2020

259次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.