C#二维非锯齿数组行处理困境:如何便捷操作替代List<List<int>>?
解决C#二维非锯齿数组的行操作问题
C#的int[,]二维数组因内存为连续单一块存储(和C++静态二维数组内存布局类似),不同于锯齿数组的“数组的数组”结构,所以语言层面未直接提供整行访问语法,但可通过以下方式解决你的需求:
1. 编写扩展方法封装行提取
给int[,]添加扩展方法,让它支持行访问,之后就能直接用LINQ操作:
public static class TwoDArrayExtensions { public static IEnumerable<int> GetRow(this int[,] array, int rowIndex) { int colCount = array.GetLength(1); for (int col = 0; col < colCount; col++) { yield return array[rowIndex, col]; } } }
使用示例:
int[,] arr = new int[10,10]; // 对第0行求和 int rowSum = arr.GetRow(0).Sum();
2. 用Span高效提取行(无额外内存分配)
追求性能的话,Span<T>可直接在原数组内存上切片,避免枚举开销:
int[,] arr = new int[10,10]; int colCount = arr.GetLength(1); // 获取第0行的Span Span<int> rowSpan = arr.AsSpan().Slice(0 * colCount, colCount); int rowSum = rowSpan.Sum();
3. 封装Matrix类(适合频繁行操作场景)
如果代码大量涉及矩阵行操作,封装专用类会让代码更整洁:
public class IntMatrix { private readonly int[,] _innerArray; public int RowCount => _innerArray.GetLength(0); public int ColCount => _innerArray.GetLength(1); public IntMatrix(int rows, int cols) { _innerArray = new int[rows, cols]; } public int this[int row, int col] { get => _innerArray[row, col]; set => _innerArray[row, col] = value; } public IEnumerable<int> GetRow(int rowIndex) { for (int col = 0; col < ColCount; col++) { yield return _innerArray[rowIndex, col]; } } public int SumRow(int rowIndex) => GetRow(rowIndex).Sum(); }
使用示例:
var matrix = new IntMatrix(10,10); int rowSum = matrix.SumRow(0);
补充说明
C#的int[,]设计侧重内存紧凑性,适合无需频繁单独操作行的场景;锯齿数组int[][]更灵活但内存有额外开销。通过上述方法,你可以保留二维数组的内存优势,同时获得类似C++的行操作便利性,无需切换到List<List<int>>。
内容的提问来源于stack exchange,提问作者Eduard G
相关产品推荐
相关产品推荐

