如何使用 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);
}
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP