Can someone help me assign multiple string arrays into one 2d string array?

為{幸葍}努か 提交于 2021-02-05 07:25:27

问题


In C#, can someone help me assign multiple string arrays to a 2d string array?

Here is my code:

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;

I am getting the following error for each 2d assignment:

Wrong number of indices inside []; expected 2

What am I doing wrong in the above code?

Thanks in advance.


回答1:


You have to specify both indicies for your 2D array, e.g.

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

You could extract a method to do this in a loop:

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



回答2:


You can initialize it like this:

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

MSDN: Multidimensional Arrays (C# Programming Guide)




回答3:


you can use jagged array, Like this:

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


来源:https://stackoverflow.com/questions/30435401/can-someone-help-me-assign-multiple-string-arrays-into-one-2d-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!