如何使用 C# 將集合複製到陣列?


首先將集合設定為複製 −

List < string > list1 = new List < string > ();
list1.Add("Car");
list1.Add("Bus");
list1.Add("Motorbike");
list1.Add("Train");

現在,宣告一個字串陣列並使用 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("Car");
      list1.Add("Bus");
      list1.Add("Motobike");
      list1.Add("Train");

      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-Jun-2020

142 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.