开发者

multidimension arraylist c#

I want to create a multi-dimension ArrayList - I don't know the size, it should 开发者_开发百科be decided at runtime.

how will I do that and how to access it?

It will be array of integers.


Use

List<List<Integer>>

List by itself isn't multidimensional -- but you can use it to store Lists, which can then store Integers, in effect acting as a multidimensional array. You can then access elements as:

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

To populate the list with initial elements, with dimensions 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
    }
}


An ArrayList is not generic, hence you cannot specify what it will contain. I would suggest using a regular generic List:

List<List<int>>

And for the accessing, just reference it by indices:

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


Instead of potentially jagged lists you could also use a 2D array created with the Array.CreateInstance method if it never needs to change size after its created.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜