如何正确初始化和填充多维数组?

时间:2017-06-27 15:18:49

标签: c# arrays multidimensional-array

如何正确初始化和填充多维数组?

string[] thisCanVaryInLength = new string[3] {"col1,nam1","col2,nam2","col3,nam3"};

string[,] columnsAndTheirNames = ?? //Unsure how to initialize

for (int i = 0; i < thisCanVaryInLength.Length; i++)
{
    columnsAndTheirNames[i, 0] = thisCanVaryInLength[0];
    columnsAndTheirNames[i, 1] = thisCanVaryInLength[1];
}

4 个答案:

答案 0 :(得分:2)

怎么样:

string[,] columnsAndTheirNames = new string[thisCanVaryInLength.Length, 2];

或带值:

string[,] columnsAndTheirNames = new string[,] { 
                 {"col1,nam1", "col2,nam2"},
                 {"col1,nam1", "col2,nam2"},
                 {"col1,nam1", "col2,nam2"}};

这是您当前的代码所做的,但也许您想要这个:

string[,] columnsAndTheirNames = new string[,] { 
                 {"col1", "nam1"},
                 {"col2", "nam2"},
                 {"col3", "nam3"}};

答案 1 :(得分:1)

分配二维数组有两种方法

方法1:

在这里,您使用空字符串

初始化它
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

答案 2 :(得分:0)

这个怎么样?

private static string[,] columnsAndTheirNames = new string[,]
{
    { "col1", "nam1" },
    { "col2", "nam2" },
    { "col3", "nam3" }
};

private void foo() {
    Console.WriteLine(columnsAndTheirNames [0, 0]); // col1
    Console.WriteLine(columnsAndTheirNames [0, 1]); // nam1
    Console.WriteLine(columnsAndTheirNames [1, 0]); // col2
    Console.WriteLine(columnsAndTheirNames [1, 1]); // nam2
}

答案 3 :(得分:0)

string[,] values =
{
  {"col1","val1"},
  {"col2","val2"},
  {"col3","val3"},
};

在调试器中查看它的外观。