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


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

更新於: 21-6 月-2020

656 次瀏覽

開啟您的 職業

完成課程來獲得認證

開始
廣告
© . All rights reserved.