像一个简单的数组一样思考:

Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());

string[] strA = new string[x];

strA[0] = "Hello";
strA[1] = "World";

for(int i = 0;i < x;i++)
{
    Console.WriteLine(strA[i]);
}


现在,我该如何使用双数组?

我已经尝试过了:

Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());

// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y];

strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys";

for(int i = 0;i < x;i++)
{
    for(int j = 0;i < y;i++)
    {
        // How can I see the items?
        Console.WriteLine(strA[i][j]);
    }
}


如果有更简单的方法,我将很高兴学习。

这只是为了知识,我是第一次学习双数组,所以请耐心等待:)

这是我的示例:
https://dotnetfiddle.net/PQblXH

最佳答案

您正在使用锯齿状数组(即数组string[][]的数组),而不是二维数组(string[,]

如果要硬编码:

  string[][] strA = new string[][] { // array of array
    new string[] {"Hello", "World"}, // 1st line
    new string[] {"Thanks", "Guys"}, // 2nd line
  };


如果您想提供xy

  string[][] strA = Enumerable
    .Range(0, y)                   // y lines
    .Select(line => new string[x]) // each line - array of x items
    .ToArray();


最后,如果我们要在不使用Linq的情况下初始化strA,但要很好地处理所有for循环(与2d数组不同,锯齿状数组可以包含不同长度的内部数组):

  // strA is array of size "y" os string arrays (i.e. we have "y" lines)
  string[][] strA = new string[y][];

  // each array within strA
  for (int i = 0; i < y; ++i)
    strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)


编辑:让我们逐行打印出锯齿状的数组:

好旧的for循环

  for (int i = 0; i < strA.Length; ++i) {
    Console.WriteLine();

    // please, note that each line can have its own length
    string[] line = strA[i];

    for (int j = 0; j < line.Length; ++j) {
      Console.Write(line[j]); // or strA[i][j]
      Console.Write(' ');     // delimiter, let it be space
    }
  }


紧凑的代码:

  Console.Write(string.Join(Environment.newLine, strA
    .Select(line => string.Join(" ", line))));

关于c# - 如何制作锯齿阵列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55300957/

10-14 11:07