【问题标题】:Can someone help me assign multiple string arrays into one 2d string array?有人可以帮我将多个字符串数组分配到一个二维字符串数组中吗?
【发布时间】:2015-08-06 18:15:53
【问题描述】:

在 C# 中,有人可以帮我将多个字符串数组分配给一个二维字符串数组吗?

这是我的代码:

string[] test1 = new string[5] { "one", "two", "three", "four", "five" };
string[] test2 = new string[5] { "one", "two", "three", "four", "five" };
string[] test3 = new string[5] { "one", "two", "three", "four", "five" };
string[] test4 = new string[5] { "one", "two", "three", "four", "five" };

string[,] allTestStrings = new string [4, 5];
allTestStrings[0] = test1;
allTestStrings[1] = test2;
allTestStrings[2] = test3;
allTestStrings[3] = test4;

对于每个 2d 分配,我都收到以下错误:

[] 内的索引数量错误;预计 2

我在上面的代码中做错了什么?

提前致谢。

【问题讨论】:

  • 多维数组 ([,]) 不是交错数组 ([],[])。

标签: c# arrays string multidimensional-array variable-assignment


【解决方案1】:

你必须为你的二维数组指定两个索引,例如

allTestStrings[0, 0] = test1[0];
allTestStrings[0, 1] = test1[1];

您可以在循环中提取一个方法来执行此操作:

for (var i = 0; i < test1.Length; i++)
{
    allTestStrings[0, i] = test1[i];
}

【讨论】:

    【解决方案2】:

    你可以这样初始化它:

    string[,] arr = {
                        { "one", "two", "three", "four", "five" },
                        { "one", "two", "three", "four", "five" },
                        { "one", "two", "three", "four", "five" },
                    };
    

    MSDN: Multidimensional Arrays (C# Programming Guide)

    【讨论】:

      【解决方案3】:

      你可以使用锯齿状数组,像这样:

      string[][] allTestStrings = new string[4][];
                  allTestStrings[0] = test1;
                  allTestStrings[1] = test2;
                  allTestStrings[2] = test3;
                  allTestStrings[3] = test4;
      

      【讨论】:

        猜你喜欢
        • 2021-12-07
        • 2021-06-12
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        • 1970-01-01
        • 1970-01-01
        • 2016-04-06
        • 1970-01-01
        相关资源
        最近更新 更多