如何在网格中显示2d数组?

时间:2016-04-30 19:09:23

标签: c# multidimensional-array

string userName = Console.ReadLine(); 


string[,] stats = new string[5,5];
stats[1,0] = "Name: ";
stats[1,1] = "userName";

我知道这可能不是最有效的做事方式,但我是新手,只是在玩C#。我该如何显示?每次我尝试它时总是将它们显示在彼此之上。

1 个答案:

答案 0 :(得分:2)

使用for循环:

for (var i = 0; i < stats.GetLength(0); i++) {
  for (var j = 0; j < stats.GetLength(1); j++)
    Console.Write("{0} ", stats[i, j]);
  Console.WriteLine();
}

这是一个基于LINQ的解决方案:

string[,] stats = new string[3,3] {
  { "Name:", "userName", "some stat" },
  { "More stat:", "more", "more" },
  { "Even more:", "hey", "great" }
};
var lines = stats.Cast<string>()
                 .Select((v, i) => new { Idx = i, Val = v })
                 .GroupBy(x => x.Idx / stats.GetLength(1))
                 .Select(x => string.Join(" ", x.Select(y => y.Val)));
Console.WriteLine(string.Join(Environment.NewLine, lines));

打印

  

名称:userName some stat

     

更多统计信息:更多

     

更多:嘿,很棒