【发布时间】:2011-11-11 05:55:56
【问题描述】:
假设我们有一个锯齿状数组
int[][] a = { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 }, new[] { 9, 10, 11, 12 } };
要得到第二行和第二列的和,可以分别写成两行代码:
int rowSum = a[1].Sum();
int colSum = a.Select(row => row[1]).Sum();
但是如果我们有二维数组的定义
int[,] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
由于编译器错误,上述代码将无法工作:
Error 1 Wrong number of indices inside []; expected 2
Error 2 'int[*,*]' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'int[*,*]' could be found (are you missing a using directive or an assembly reference?)
那么,问题来了:如何将 LINQ 方法用于 n 维数组,而不是锯齿状数组?以及将矩形数组转换为锯齿状的方法在哪里?
附:我试图在文档中找到答案,但没有结果。
【问题讨论】:
-
C# 并不真正(广泛)支持多维数组 :-(