以矩阵格式打印2Darrays

我有一个2D数组如下:

long[,] arr = new long[4, 4] {{ 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }}; 

我想以矩阵格式打印这个数组的值,如:

 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 

我怎样才能做到这一点?

您可以这样做(使用稍微修改过的数组来显示它适用于非方形数组):

  long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int rowLength = arr.GetLength(0); int colLength = arr.GetLength(1); for (int i = 0; i < rowLength; i++) { for (int j = 0; j < colLength; j++) { Console.Write(string.Format("{0} ", arr[i, j])); } Console.Write(Environment.NewLine + Environment.NewLine); } Console.ReadLine(); 

像这样:

 long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } }; var rowCount = arr.GetLength(0); var colCount = arr.GetLength(1); for (int row = 0; row < rowCount; row++) { for (int col = 0; col < colCount; col++) Console.Write(String.Format("{0}\t", arr[row,col])); Console.WriteLine(); } 

以下是如何在Unity中执行此操作:

(来自@markmuetz的修改后的回答所以一定要提出他的回答 )

 int[,] rawNodes = new int[,] { { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 } }; private void Start() { int rowLength = rawNodes.GetLength(0); int colLength = rawNodes.GetLength(1); string arrayString = ""; for (int i = 0; i < rowLength; i++) { for (int j = 0; j < colLength; j++) { arrayString += string.Format("{0} ", rawNodes[i, j]); } arrayString += System.Environment.NewLine + System.Environment.NewLine; } Debug.Log(arrayString); } 

你可以在短时间内这样做。

  int[,] values=new int[2,3]{{2,4,5},{4,5,2}}; for (int i = 0; i < values.GetLength(0); i++) { for (int k = 0; k < values.GetLength(1); k++) { Console.Write(values[i,k]); } Console.WriteLine(); } 

你也可以这样做

  long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }}; for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { Console.Write(arr[i,j]+" "); } Console.WriteLine(); }