Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create an array of list objects

Tags:

c#

collections

I have a line of code like this:

List<string>[] apples = new List<string>()[2];

Its purpose is simply to create an array of List objects. When I try to compile my code, the above line generates this error:

Cannot implicitly convert type 'string' to 'System.Collections.Generic.List[]

I haven't been able to find much on the subject of creating an array of List objects (actually only this thread), maybe because no search engines will search for brackets.

Is the only way to create a collection of Lists to put them in another list, like below?

List<List<string>> apples = new List<List<string>>(); //I've tried this and it works as expected

Thanks for any suggestions, I'm really just curious as to why the first line of code (the List[] example) doesn't work.

like image 455
Brian Snow Avatar asked Feb 10 '12 00:02

Brian Snow


People also ask

Can you create an array of objects?

Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types.

Can you make an array of lists in Python?

Lists can be converted to arrays using the built-in functions in the Python numpy library. numpy provides us with two functions to use when converting a list into an array: numpy. array()


2 Answers

You can do this. The syntax would be:

List<string>[] apples = new List<string>[2];

Note that this only allocates an array of references - you'll need to actually construct the individual list elements before you use them:

List<string>[] apples = new List<string>[2];
apples[0] = new List<string>();
apples[1] = new List<string>();

Alternatively, you can use the collection initialization syntax (works well for small numbers of fixed elements), ie:

List<string>[] apples = new[] { new List<string>(), new List<string>() };
like image 132
Reed Copsey Avatar answered Sep 19 '22 15:09

Reed Copsey


Try this:

List<string>[] apples = new List<string>[2];

You do the initialization of each list afterwards:

apples[0] = new List<string>();
like image 26
xbrady Avatar answered Sep 22 '22 15:09

xbrady