这是二维数组:
int[][] array2D = new int[7][];
for (int i = 0; i < 7; i++)
array2D[i] = new int[7];
如何将以下内容转换为LINQ查询,或使用可枚举方法来实现相同的输出?
var lst = new List<Point>();
for (int r = 0; r < array2D.Length; r++)
for (int c = 0; c < array2D[r].Length; c++)
if (array2D[r][c] == 0)
lst.Add(new Point(c, r));
编辑 - 基于@'King King的答案的解决方案
var lst = m_boardArr.SelectMany((row, rowIndex) =>
row.Select((val, colIndex) =>
new { val, point = new Point(colIndex, rowIndex) })
.Where(col => col.val == 0)
.Select(col => col.point)).ToList();
答案 0 :(得分:1)
var lst = array2D
.SelectMany((innerArray, r)
=> Enumerable
.Range(0, innerArray.Length)
.Where(c => innerArray[c] == 0)
.Select(c => new Point(c, r)))
.ToList();
但是,您当前的解决方案更具可读性。
答案 1 :(得分:1)
试试这个:
var lst = array2D.SelectMany((x,r) => x.Select((a,c)=> new {a,b=new Point(c,r)})
.Where(a=>a.a==0)
.Select(a=>a.b)).ToList();
答案 2 :(得分:1)
诀窍是使用捕获循环变量的Select
和SelectMany
成为匿名类型,然后在Where
子句之后获取这些属性,因此:
var list = array2D
.SelectMany((row, r) => row
.Select((el, c) =>
new {Element = el, ColIndex = c, RowIndex = r})
.Where(thing => thing.Element == 0)
.Select(thing => new Point(thing.RowIndex, thing.ColIndex)))
.ToList();
编辑:Bartosz的评论也适用于此解决方案。不可读!