C# 如何将列表复制到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1921701/
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
How to copy List to Array
提问by Captain Comic
I have list of Guid's
我有 Guid 的列表
List<Guid> MyList;
I need to copy its contents to Array
我需要将其内容复制到 Array
Guid[]
Please recommend me a pretty solution
请推荐我一个漂亮的解决方案
采纳答案by Romain Verdier
As Lukesaid in comments, the particular List<T>
type already has a ToArray()
method. But if you're using C# 3.0, you can leverage the ToArray()
extension method on any IEnumerable
instance (that includes IList
, IList<T>
, collections, other arrays, etc.)
正如Luke在评论中所说,特定List<T>
类型已经有一个ToArray()
方法。但是,如果您使用的是 C# 3.0,则可以ToArray()
在任何IEnumerable
实例(包括IList
、IList<T>
、集合、其他数组等)上利用扩展方法
var myList = new List<Guid> {Guid.NewGuid(), Guid.NewGuid()};
Guid[] array = myList.ToArray(); // instance method
IList<Guid> myList2 = new List<Guid> {Guid.NewGuid(), Guid.NewGuid()};
Guid[] array2 = myList2.ToArray(); // extension method
var myList3 = new Collection<Guid> {Guid.NewGuid(), Guid.NewGuid()};
Guid[] array3 = myList3.ToArray(); // extension method
Regarding your second question:
关于你的第二个问题:
You can use the Select
method to perform the needed projection:
您可以使用该Select
方法执行所需的投影:
var list = new List<MyClass> {new MyClass(), new MyClass()};
Guid[] array = list.Select(mc => mc.value).ToArray();
回答by Adam Gritt
You should just have to call MyList.ToArray() to get an array of the elements.
您应该只需要调用 MyList.ToArray() 来获取元素数组。
回答by Winston Smith
Using the Enumerable.ToArray() Extension Methodyou can do:
使用Enumerable.ToArray() 扩展方法,您可以执行以下操作:
var guidArray = MyList.ToArray();
If you're still using C# 2.0 you can use the List.ToArraymethod. The syntax is the same (except there's no var
keyword in C# 2.0).
如果您仍在使用 C# 2.0,则可以使用List.ToArray方法。语法是相同的(除了var
C# 2.0 中没有关键字)。
回答by tvanfosson
The new way (using extensions or the ToArray() method on generic lists in .Net 2.0):
新方法(在 .Net 2.0 中的泛型列表上使用扩展或 ToArray() 方法):
Guid[] guidArray = MyList.ToArray();
The old way:
旧方法:
Guid[] guidArray = new guidArray[MyList.Length];
int idx = 0;
foreach (var guid in MyList)
{
guidArray[idx++] = guid;
}
回答by Dan Tao
Yet another option, in addition to Guid[] MyArray = MyList.ToArray()
:
另一个选择,除了Guid[] MyArray = MyList.ToArray()
:
Guid[] MyArray = new Guid[MyList.Count]; // or wherever you get your array from
MyList.CopyTo(MyArray, 0);
This solution might be better if, for whatever reason, you already have a properly-sized array and simply want to populate it (rather than construct a new one, as List<T>.ToArray()
does).
如果出于某种原因,您已经有一个大小合适的数组并且只想填充它(而不是像List<T>.ToArray()
那样构造一个新数组),则此解决方案可能会更好。