I want to have an array of Lists. In c++ I do like:

List<int> a[100]; 

which is an array of 100 Lists. each list can contain many elements. I don't know how to do this in c#. Can anyone help me?

7 Answers

You do like this:

List<int>[] a = new List<int>[100]; 

Now you have an array of type List<int> containing 100 null references. You have to create lists and put in the array, for example:

a[0] = new List<int>(); 

Since no context was given to this question and you are a relatively new user, I want to make sure that you are aware that you can have a list of lists. It's not the same as array of list and you asked specifically for that, but nevertheless:

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

you can initialize them through collection initializers like so:

List<List<int>> myList = new List<List<int>>(){{1,2,3},{4,5,6},{7,8,9}}; 
1

simple approach:

 List<int>[] a = new List<int>[100]; for (int i = 0; i < a.Length; i++) { a[i] = new List<int>(); } 

or LINQ approach

 var b = Enumerable.Range(0,100).Select((i)=>new List<int>()).ToArray(); 
List<int>[] a = new List<int>[100]; 

You still would have to allocate each individual list in the array before you can use it though:

for (int i = 0; i < a.Length; i++) a[i] = new List<int>(); 

I can suggest that you both create and initialize your array at the same line using linq:

List<int>[] a = new List<int>[100].Select(item=>new List<int>()).ToArray(); 

use

List<int>[] a = new List<int>[100]; 
// The letter "t" is usually letter "i"// for(t=0;t<x[t];t++) { printf(" %2d || %7d \n ",t,x[t]); } 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy