使用LINQ与n维阵列数组操作(C#) [英] Array operations with n-dimensional array using LINQ (C#)
问题描述
假设我们有一个锯齿形阵列
Assume we have a jagged array
int[][] a = { new[] { 1, 2, 3, 4 }, new[] { 5, 6, 7, 8 }, new[] { 9, 10, 11, 12 } };
要获得第二行第二列的总和的总和,它可以被分别写入两个code线:
To get a sum of second row and sum of second column, it can be written both code lines respectively:
int rowSum = a[1].Sum();
int colSum = a.Select(row => row[1]).Sum();
但是,如果我们有2维数组的定义
But if we have definition of 2-dimensional array
int[,] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
以上引用code将无法正常工作,由于compiller错误:
the above-cited code will not work due to compiller errors:
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维数组,而不是锯齿状的?而正是一种方法来矩形阵列转换成锯齿状?
So, the question: How to use LINQ methods with n-dimensional arrays, but not jagged ones? And is where a method to convert rectangular array to jagged?
P.S。我试图找到在文档中的答案,但没有结果。
P.S. I tried to find the answer in documentation, but without result.
推荐答案
LINQ到对象是基于的IEnumerable< T>接口时,即,值的一维的序列。这意味着它不会像非交错数组n维数据结构拌匀,虽然它是可能的。
LINQ to Objects is based on the IEnumerable<T> Interface, i.e. a one-dimensional sequence of values. This means it doesn't mix well with n-dimensional data structures like non-jagged arrays, although it's possible.
可以生成整数的一维的序列索引的n维阵列
You can generate one-dimensional sequence of integers that index into the n-dimensional array:
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]);
这篇关于使用LINQ与n维阵列数组操作(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!