How to create an array of List<int> in C#?
I have a problem where I need an arra开发者_JAVA百科y of arrayList.
For example if we take an Array of ArrayList of int, it will be like:
int[]<List> myData = new int[2]<List>;
myData[0] = new List<int>();
myData[0].Add(1);
myData[0].Add(2);
myData[0].Add(3);
myData[1] = new List<int>();
myData[1].Add(4);
myData[1].Add(5);
myData[1].Add(6);
myData[0].Add(7);
How can we implement a datastructure like the above in C#?
In C, its like a array of LinkedList. How can I do the same in C#?
var myData = new List<int>[]
{
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 }
};
Almost as you tried, only the first line is incorrect:
List<int>[] myData = new List<int>[2];
myData[0] = new List<int>();
myData[0].Add(1);
myData[0].Add(2);
myData[0].Add(3);
myData[1] = new List<int>();
myData[1].Add(4);
myData[1].Add(5);
myData[1].Add(6);
myData[0].Add(7);
Thanks to madmik3, here is a link you can read something about generic lists in C#: click me
Also, if you want to read something about arrays, e.g. the static copy method of the Array
class, here is some link for that.
var arraySize = 2;
var myArray = new List<Int32>[arraySize];
myArray[0] = new List<Int32>();
myArray[1] = new List<Int32>();
// And so on....
myArray[0].Add(5);
I prefer lists but it's up to you...
List<List<int>> lst = new List<List<int>>();
lst.Add(new List<int>());
lst.Add(new List<int>());
lst[0].Add(1);
lst[1].Add(1);
lst[1].Add(2);
lst[0].Add(5);
Then if you really want a list at the end of it all use some linq.
lst.ToArray();
You're trying to take the concrete type List<int>
and make an array of it.
Just like string
becomes new string[2]
, so to List<int>
becomes new List<int>[2]
.
This will create an array which can hold two List<int>
s.
However, each element in the array starts out null
.
You'll need to put a new List<int>()
into each slot of the array before using it.
However, you should probably use a List<List<int>>
instead of an array of lists.
精彩评论