多维arraylist c#

时间:2011-05-26 21:06:41

标签: c# c#-2.0

我想创建一个多维ArrayList - 我不知道它的大小,应该在运行时决定。

我将如何操作以及如何访问它?

它将是整数数组。

3 个答案:

答案 0 :(得分:2)

使用

List<List<Integer>>

列表本身不是多维的 - 但您可以使用它来存储列表,然后可以存储整数,实际上充当多维数组。然后,您可以访问元素:

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

使用尺寸为x和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
    }
}

答案 1 :(得分:2)

ArrayList不是通用的,因此您无法指定它将包含的内容。 我建议使用常规通用列表:

List<List<int>>

对于访问,只需通过索引引用它:

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

答案 2 :(得分:0)

如果在创建后永远不需要更改大小,您也可以使用使用Array.CreateInstance方法创建的2D数组,而不是潜在的锯齿状列表。

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]);