Converting a list to an array with ToArray()

2019-04-06 19:51发布

I've 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, thereby using:

listItem[] myArray = myList.ToArray();

Unfortunately, this doesn't work, and I get this error message:

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

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

Thanks in advance.

EDIT: My bad, the first code line I wrote was indeed mistyped!

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

List<listItem> myFunction()

returned myArray, hence the conversion problem... It is now fixed. :)

Thank you all for your answers.

3条回答
我只想做你的唯一
2楼-- · 2019-04-06 20:26

This is the error (as pointed out from Darkshadw and Jon Skeet)

listItem myList = new List<listItem>();

You are assigning the value of a List to a listItem.

Replace it with

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

to create a list of listItem. Then

listItem[] myArray = myList.ToArray();

will work.

查看更多
霸刀☆藐视天下
3楼-- · 2019-04-06 20:37

have you tried

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

in Java it works, im not sure in c#

查看更多
forever°为你锁心
4楼-- · 2019-04-06 20:42
string[] s = myList.ToArray();

Considering myList is list of string

查看更多
登录 后发表回答