c#访问二维数组中的行

时间:2012-02-18 17:27:43

标签: c# arrays rows multidimensional-array

如何在C#中访问一行二维数组?我想得到第一排的数量。

谢谢!

2 个答案:

答案 0 :(得分:7)

问题实际上取决于您正在考虑的2D阵列的类型以及您的行的维度。

正确的二维数组

// Init
var arr = new int[5,10];

// Counts
arr.GetLength(0) // Length of first dimension: 5
arr.GetLength(1) // Length of second dimension: 10

锯齿状的“2D”数组

// Init
var arr = new int[3][];
// Initially arr[0],arr[1],arr[2] is null, so we have to intialize them:
arr[0] = new int[5];
arr[1] = new int[4];
arr[2] = new int[2];

// Counts
arr.Length // Length of first dimension
// In this case the "second dimension" (if you can call it that) is of variable size
arr[0].Length // Length: 5
arr[1].Length // Length: 4
arr[2].Length // Length: 2

答案 1 :(得分:0)

这也可以,

string[,] a = new string[,]
{
    {"ant", "aunt"},
    {"Sam", "Samantha"},
    {"clozapine", "quetiapine"},
    {"flomax", "volmax"},
    {"toradol", "tramadol"}
};

// a[1,1] is equal to Samantha