Convert list to array using ToArray ()

I created a class called listItem and the following list:

List<listItem> myList = new List<listItem>(); 

At some point in my code, I want to convert it to an array using:

 listItem[] myArray = myList.ToArray(); 

Unfortunately, this does not work, and I get this error message:

 Cannot convert [...] listItem[] to [...] List<listItem> 

I tried to figure it out, but very unsuccessfully ...

Thanks in advance.

EDIT: My failure, the first line of code I wrote was really wrong!

Actually, all the code above works very well. My error was due to the fact that my function:

 List<listItem> myFunction() 

returns myArray, therefore the conversion problem ... Now it is fixed. :)

Thank you all for your answers.

+7
source share
4 answers

This is a mistake (as stated in Darkshadw and Jon Skeet)

 listItem myList = new List<listItem>(); 

You are assigning a List ListItem value.

Replace it

 List<listItem> myList = new List<listItem>(); 

to create a listItem list. Then

 listItem[] myArray = myList.ToArray(); 

will work.

+9
source

You tried

 listItem[] myArray = myList.ToArray(new listItem[]{}); 

in Java it works, im not sure about C #

+2
source

Try using the var keyword:

 var myList = new List<listItem>(); var myArray = myList.ToArray(); 
0
source
 string[] s = myList.ToArray(); 

Given that myList is a list of strings

0
source

All Articles