如何將 List 集合複製到陣列?


要將 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-06-21

656 次瀏覽

開啟您的 職業生涯

透過完成課程進行認證

開始
廣告
© . All rights reserved.