How to create a List <int> array in C #?
I have a problem when I need an arrayList array.
For example, if we take an ArrayList from int, it will look like this:
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 data structure like the one above in C #?
In C, it looks like a LinkedList array. 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 the way 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 about shared lists in C #: click me
Also, if you want to read something about arrays, for example. method of a static copy of the Array class, here is a reference for this.
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 the list at the end of this all use some linq.
lst.ToArray(); You are trying to take a specific type of List<int> and create its array.
Just like a string it becomes a new string[2] , so before List<int> it becomes a new List<int>[2] .
This will create an array that can contain two List<int> s.
However, each element of the array begins null .
Before use, you need to put new List<int>() in each slot of the array.
However, most likely you should use List<List<int>> instead of an array of lists.