How can I convert a list to an array?
I'm trying to call a method but it's telling me that I need to pass in an array. There is no Convert.ToArray() method, and casting doesn't work.
How can I convert开发者_如何学编程 a list to an array?
You shouldn't use Arraylists (your question is tagged arraylist) in the first place. They are deprecated as of C# 2 and generics (Use List<int>
for dynamically sized collection of integers for example). Then, if you have C# 3.5 and later you should use the aforementioned .ToArray()
extension method. And if you don't have the latest and greatest C#, you can use
ArrayList arraylist= new ArrayList();
arraylist.Add( 1 );
arraylist.Add( 2 );
arraylist.Add( 3 );
int[] mydatas = (int[]) arraylist.ToArray(typeof(int));
You can with System.Linq.Enumerable.ToArray
:
using System.Linq;
...
var b = a.ToArray();
Call the ToArray() method on your list object. I have provided a link to the documentation.
This documentation refers to the System.Collections.Generic namespace which is available in all versions of .NET unlike the more specialized linq namespace. They do perform the same function, however no details on performance comparisons are provided here.
MSDN documentation on List.ToArray Method
Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)
public T[] ToArray()
Try
yourList.ToArray()
is part of the Enumerable extension methods
精彩评论