从List <t>转换为数组T [] </t>

时间:2009-03-10 07:13:48

标签: c# .net arrays linq list

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

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

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

7 个答案:

答案 0 :(得分:124)

尝试使用

MyClass[] myArray = list.ToArray();

答案 1 :(得分:15)

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

是你的解决方案吗?

答案 2 :(得分:8)

ToArray()上使用List<T>

答案 3 :(得分:8)

list.ToArray()

会做三重奏。有关详细信息,请参阅here

答案 4 :(得分:0)

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

示例:

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

  

使用Array.Copy()复制元素,using CustomConsole.Common; using System; using System.Collections.Generic; using System.IO; namespace Shell_Commander.Commands { class FindFileCommand : ICommand { private string _findFileCommandName = "findfile"; public string Name { get { return _findFileCommandName; } set { _findFileCommandName = value; } } public string Execute(string parameters) { var fileLocations = new Dictionary<string, bool>(); try { var splittedParameters = parameters.Split(" "); var initialLocation = splittedParameters[0]; var fileName = splittedParameters[1]; foreach (var filePath in Directory.GetFiles(initialLocation, "*.*", SearchOption.A­llDirectories)) { fileLocations.Add(filePath, false); if (Path.GetFileName(filePath) == fileName || Path.GetFileNameWithoutExtension(filePath) == fileName) { fileLocations[filePath] = true; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } bool fileFound = false; string returnedOutput = ""; foreach (var location in fileLocations.Keys) { if (fileLocations[location]) { returnedOutput += $"The file found in path: {location}\n"; Console.Write(returnedOutput); fileFound = true; } } if (!fileFound) { returnedOutput = "The file not found in this path"; Console.WriteLine(returnedOutput); return returnedOutput; } return returnedOutput; } } } 是O(n)操作,   其中n是计数。

答案 5 :(得分:-1)

通过使用多个处理器内核使速度快两倍,HPCsharp nuget软件包提供了:

list.ToArrayPar();

答案 6 :(得分:-1)

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

list.AsParallel().ToArray();