我有int数组表示方阵的元素。我需要获得它的行,列,2个主要对角线。我在获得第二个对角线方面遇到了麻烦(对于3 * 3矩阵,它是6 * 6 - 5,10,15,20,25,30的索引2,4,6的元素)。我想知道是否有一种简洁的方法可以在没有循环的情况下完成它。
var matrix = new int[] { 6, 7, 2, 1, 5, 9, 8, 3, 4 };
int size = 3;
int i = 0;
var rows = matrix.GroupBy(x => i++ / size);
i = 0;
var columns = matrix.GroupBy(x => i++ % size);
var diag1 = matrix.Where((x, index)=>index%(size+1)==0);
var diag2 = matrix.Where((x, index) => index % (size - 1) == 0);//PROBLEM - takes 0,8 indexes also.
答案 0 :(得分:1)
试试这个
var matrix = new int[] { 6, 7, 2, 1, 5, 9, 8, 3, 4 };
int size = 3;
var rows = matrix.Select((x,i) => new {x = x, i = i}).GroupBy(x => x.i / size).Select(x => x.Select(y => y.x).ToArray()).ToArray();
var columns = matrix.Select((x, i) => new { x = x, i = i }).GroupBy(x => x.i % size).Select(x => x.Select(y => y.x).ToArray()).ToArray();
var diag1 = matrix.Where((x, index) => (index /size) == (index % size)).Select(x => x).ToArray();
var diag2 = matrix.Where((x, index) => (index / size) == (size - 1) - (index % size)).Select(x => x).ToArray();