Lonnie Schultz
Lonnie Schultz

Reputation: 104

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?

Upvotes: 1

Views: 178

Answers (4)

Gleno
Gleno

Reputation: 16969

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));

Upvotes: 3

Moog
Moog

Reputation: 10193

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()

Upvotes: 0

Jaime
Jaime

Reputation: 6814

Try

yourList.ToArray()

is part of the Enumerable extension methods

Upvotes: 0

manojlds
manojlds

Reputation: 301527

You can with System.Linq.Enumerable.ToArray:

using System.Linq;
...
var b = a.ToArray();

Upvotes: 2

Related Questions