【发布时间】:2017-02-11 05:00:09
【问题描述】:
给定下面的二维矩阵
int[][] m = new int[][] { new int[] { 1, 2, 3, 4 },
new int[] { 0, 1, 4, 3 },
new int[] { 4, 0, 2, 2 },
new int[] { 4, 2, 0, 1 }};
我想使用 LINQ 来获取所有对角线,即
4
3 3
2 4 2
1 1 2 1
0 0 0
4 2
4
现在我正在使用两个丑陋的 for 循环,但我知道必须有更好的方法。
List<List<int>> e = new List<List<int>>();
for (int i = 0; i < m.Count(); i++)
{
for (int j = m.Count() - 1; j >= 0; j--)
{
if (i == 0 || (i > 0 && j == 0))
{
e.Add(new List<int> { m[i][j] });
}
if (i > 0 && j > 0)
{
e[i - j + m.Count() - 1].Add(m[i][j]);
}
}
}
【问题讨论】: