List <T>.ToArray()方法用于将所有列表元素复制到新数组,或者可以说它用于将列表转换为数组。
语法:
T[] List<T>.ToArray();
参数:无
返回值:返回T类型的数组
示例
int list declaration: List<int> a = new List<int>(); //将列表元素复制到新数组 int[] arr = a.ToArray(); Output: arr: 10 20 30 40 50
using System;
using System.Text;
using System.Collections.Generic;
namespace Test
{
class Program
{
static void printList(List<int> lst)
{
//打印元素
foreach (int item in lst)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//整数列表
List<int> a = new List<int>();
//添加元素
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
//打印列表
Console.WriteLine("list elements...");
printList(a);
//将列表元素复制到新数组
int[] arr = a.ToArray();
//打印类型
Console.WriteLine("type of a: " + a.GetType());
Console.WriteLine("type of arr: " + arr.GetType());
//打印列表
Console.WriteLine("array elements...");
foreach (int item in arr)
{
Console.Write(item + " ");
}
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
list elements... 10 20 30 40 50 type of a: System.Collections.Generic.List`1[System.Int32] type of arr: System.Int32[] array elements... 10 20 30 40 50