1

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?

4 Answers 4

3

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));
Sign up to request clarification or add additional context in comments.

Comments

2

You can with System.Linq.Enumerable.ToArray:

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

2 Comments

I tried that, but it gave me an error: "The type or namespace name 'Linq' does not exist in the namespace 'System'." Should it be "Link"?
@Lonnie You'll get this error if you don't reference "System.Core.dll"
0

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

Comments

0

Try

yourList.ToArray()

is part of the Enumerable extension methods

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.