有2種方式來分配一個2維數組
方法一:
在這裏,您有空字符串
初始化它
string[,] columnsAndTheirNames1 = new string[2, 3];
方法2:
在這裏你用字符串初始化它。
string[,] columnsAndTheirNames = {
{ "row1-col1", "row1-col2"},
{ "row2-col1", "row2-col2"},
{ "row3-col1", "row3-col2"}
};
在這裏,您可以看到如何訪問:
for (int i = 0; i < columnsAndTheirNames.GetLength(0); ++i) {
for (int j = 0; j < columnsAndTheirNames.GetLength(1); ++j) {
Console.Write(columnsAndTheirNames[i, j] + "\t");
}
Console.WriteLine();
}
輸出希望像下面
row1-col1 row1-col2
row2-col1 row2-col2
row3-col1 row3-col2
所以,你的代碼應該是類似下面
string[] thisCanVaryInLength = new string[3] { "col1,nam1", "col2,nam2", "col3,nam3" };
string[,] columnsAndTheirNames = new string[2, thisCanVaryInLength.Length];
for (int i = 0; i < thisCanVaryInLength.Length; i++) {
var items = thisCanVaryInLength[i].Split(',');
columnsAndTheirNames[0, i] = items[0];
columnsAndTheirNames[1, i] = items[1];
}
for (int i = 0; i < columnsAndTheirNames.GetLength(0); ++i) {
for (int j = 0; j < columnsAndTheirNames.GetLength(1); ++j) {
Console.Write(columnsAndTheirNames[i, j] + "\t");
}
Console.WriteLine();
}
,輸出是
col1 col2 col3
nam1 nam2 nam3
,我認爲它在數組內容可能會有所不同的OP,變量(thisCanVaryInLength),因此名字說,我可能是錯的。 – Rod