使用LINQ(C#)的n维数组的数组运算

Lev*_*sky 9 c# linq arrays

假设我们有一个锯齿状的数组

int[][] a = { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 }, new[] { 9, 10, 11, 12 } };
Run Code Online (Sandbox Code Playgroud)

要获得第二行和第二列之和的总和,可以分别写入两个代码行:

int rowSum = a[1].Sum();
int colSum = a.Select(row => row[1]).Sum();
Run Code Online (Sandbox Code Playgroud)

但是如果我们有二维数组的定义

int[,] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
Run Code Online (Sandbox Code Playgroud)

由于编译器错误,上述代码将无效:

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?)
Run Code Online (Sandbox Code Playgroud)

那么,问题是:如何使用具有n维数组的LINQ方法,而不是锯齿状的数组?并且是将矩形数组转换为锯齿状的方法?

PS我试图在文档中找到答案,但没有结果.

dtb*_*dtb 15

LINQ to Objects基于IEnumerable <T>接口,即一维值序列.这意味着它与n-dimensional数据结构(如非锯齿状数组)不能很好地混合,尽管它是可能的.

您可以生成索引到n维数组的一维整数序列:

int rowSum = Enumerable.Range(0, a.GetLength(1)).Sum(i => a[1, i]);

int colSum = Enumerable.Range(0, a.GetLength(0)).Sum(i => a[i, 1]);
Run Code Online (Sandbox Code Playgroud)