C# 从 List<T> 到数组 T[] 的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/629178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:58:45  来源:igfitidea点击:

Conversion from List<T> to array T[]

c#.netarrayslinqlist

提问by tehvan

Is there a short way of converting a strongly typed List<T>to an Array of the same type, e.g.: List<MyClass>to MyClass[]?

是否有将强类型转换为List<T>相同类型的数组的简短方法,例如:List<MyClass>to MyClass[]

By short i mean one method call, or at least shorter than:

简而言之,我的意思是一种方法调用,或者至少短于:

MyClass[] myArray = new MyClass[list.Count];
int i = 0;
foreach (MyClass myClass in list)
{
    myArray[i++] = myClass;
}

采纳答案by Nikos Steiakakis

Try using

尝试使用

MyClass[] myArray = list.ToArray();

回答by Brian Rasmussen

Use ToArray()on List<T>.

使用ToArray()List<T>

回答by Sessiz Saat

List<int> list = new List<int>();
int[] intList = list.ToArray();

is it your solution?

这是你的解决方案吗?

回答by Bas Bossink

list.ToArray()

Will do the tric. See herefor details.

会做的。有关详细信息,请参见此处

回答by Nipuna

You can simply use ToArray()extension method

您可以简单地使用ToArray()扩展方法

Example:

例子:

Person p1 = new Person() { Name = "Person 1", Age = 27 };
Person p2 = new Person() { Name = "Person 2", Age = 31 };

List<Person> people = new List<Person> { p1, p2 };

var array = people.ToArray();

According to Docs

根据文档

The elements are copied using Array.Copy(), which is an O(n) operation, where n is Count.

使用 复制元素Array.Copy(),这是一个 O(n) 操作,其中 n 是计数。

回答by DragonSpit

To go twice as fast by using multiple processor cores HPCsharp nuget package provides:

为了通过使用多个处理器内核将速度提高一倍,HPCsharp nuget 包提供:

list.ToArrayPar();

回答by DragonSpit

One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:

一种可能要避免的解决方案,它使用多个 CPU 内核,预计速度会更快,但它的执行速度要慢 5 倍:

list.AsParallel().ToArray();