如何获取二维数组所有行?并将网格特定行列映射到字典中
问题1:如何获取二维数组的所有行?
获取二维数组的所有行其实很直观,核心看你用的是矩形二维数组(T[,])还是交错数组(T[][]),两种类型的处理方式略有不同:
1. 矩形二维数组(T[,])
这种数组的每行长度一致,你可以通过GetLength(0)获取总行数,遍历行索引后提取每一行的元素:
// 示例:int类型的3行4列矩形数组 int[,] twoDArray = new int[3, 4] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // 遍历所有行 for (int rowIndex = 0; rowIndex < twoDArray.GetLength(0); rowIndex++) { // 提取当前行到一维数组 int[] currentRow = new int[twoDArray.GetLength(1)]; for (int colIndex = 0; colIndex < twoDArray.GetLength(1); colIndex++) { currentRow[colIndex] = twoDArray[rowIndex, colIndex]; } // 这里可以对currentRow做后续处理 Console.WriteLine($"第{rowIndex+1}行:{string.Join(", ", currentRow)}"); }
2. 交错数组(T[][])
这种数组的每行长度可以不同,但遍历更简单,直接foreach循环就能拿到每一行:
// 示例:长度不一的交错数组 int[][] jaggedArray = new int[][] { new int[] {1,2,3}, new int[] {4,5}, new int[] {6,7,8,9} }; foreach (int[] row in jaggedArray) { Console.WriteLine($"行内容:{string.Join(", ", row)}"); }
问题2:将网格特定行列值以字典形式存储
从你的需求和代码片段来看,你是要把7x7网格的四个边缘区域(排除四个角落)按方向存入字典。我帮你补全并优化了实现,逻辑更清晰还能适配不同大小的网格:
using System.Collections.Generic; using UnityEngine; void GetSpawnablePosition() { // 假设你的grid已经初始化完成(这里给个示例初始化) Vector2[][] grid = new Vector2[7][]; for (int i = 0; i < grid.Length; i++) { grid[i] = new Vector2[7]; for (int j = 0; j < grid[i].Length; j++) { grid[i][j] = new Vector2(i, j); } } // 初始化目标字典 Dictionary<Vector2, List<Vector2>> edgeDict = new Dictionary<Vector2, List<Vector2>>(); int gridRowCount = grid.Length; int gridColCount = grid[0].Length; // 处理Vector2.up:第一行(索引0)的第1到倒数第2列 List<Vector2> upPositions = new List<Vector2>(); for (int col = 1; col < gridColCount - 1; col++) { upPositions.Add(grid[0][col]); } edgeDict.Add(Vector2.up, upPositions); // 处理Vector2.left:第一列(索引0)的第1到倒数第2行 List<Vector2> leftPositions = new List<Vector2>(); for (int row = 1; row < gridRowCount - 1; row++) { leftPositions.Add(grid[row][0]); } edgeDict.Add(Vector2.left, leftPositions); // 处理Vector2.right:最后一列的第1到倒数第2行 List<Vector2> rightPositions = new List<Vector2>(); int lastCol = gridColCount - 1; for (int row = 1; row < gridRowCount - 1; row++) { rightPositions.Add(grid[row][lastCol]); } edgeDict.Add(Vector2.right, rightPositions); // 处理Vector2.down:最后一行的第1到倒数第2列 List<Vector2> downPositions = new List<Vector2>(); int lastRow = gridRowCount - 1; for (int col = 1; col < gridColCount - 1; col++) { downPositions.Add(grid[lastRow][col]); } edgeDict.Add(Vector2.down, downPositions); // 测试输出验证结果 foreach (var pair in edgeDict) { Debug.Log($"方向:{pair.Key}"); Debug.Log($"坐标列表:{string.Join(", ", pair.Value)}"); } }
几个优化细节:
- 用
grid.Length和grid[0].Length代替硬编码的7,后续网格大小变化时无需修改代码 - 用
gridRowCount - 1和gridColCount - 1获取最后一行/列索引,逻辑更通用 - 分方向独立处理,代码可读性和维护性更强
内容的提问来源于stack exchange,提问作者Crocsx
相关产品推荐
相关产品推荐

