Multidimensionality of arraylist C #

I want to create multidimensional ArrayList- I do not know the size, it needs to be solved at runtime.

How will I do this and how to access it?

It will be an array of integers.

+3
source share
3 answers

Using

List<List<Integer>>

The list itself is not multidimensional, but you can use it to store lists, which can then store integers, acting as a multidimensional array. Then you can access the elements as follows:

// Get the element at index x,y
int element = list[x][y];

To populate the list with source elements x and y:

for (int i=0; i<x; i++)
{
    // Have to create the inner list for each index, or it'll be null
    list.Add(new List<Integer>());

    for (int j=0; j<y; j++)
    {
        list[i].Add(someValue); // where someValue is whatever starting value you want
    }
}
+2
source

ArrayList is not generic, so you cannot specify what it will contain. I would suggest using a regular general list:

List<List<int>>

And for access, just specify it by index:

List<List<int>> myList = new List<List<int>>();
int item = myList[1][2];
+2

2D-, Array.CreateInstance, .

int[,] arrayOfInts = (int[,])Array.CreateInstance(typeof(int), 4, 5);

arrayOfInts[0,0] = 5;
Console.WriteLine(arrayOfInts[0,0]);

arrayOfInts[0,4] = 3;
Console.WriteLine(arrayOfInts[0,4]);
0

All Articles