An array of List in c#
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?
Solution 1:
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>();
Solution 2:
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}};
Solution 3:
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();
Solution 4:
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>();
Solution 5:
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();