1

这是二维数组:

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's answer的解决方案

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();
4

3 回答 3

1
var lst = array2D
    .SelectMany((innerArray, r)
        => Enumerable
               .Range(0, innerArray.Length)
               .Where(c => innerArray[c] == 0)
               .Select(c => new Point(c, r)))
    .ToList();

但是,您当前的解决方案更具可读性。

于 2013-09-28T18:56:04.930 回答
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();
于 2013-09-28T18:56:32.880 回答
1

诀窍是使用Selectand将循环变量捕获为匿名类型,然后在子句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 的评论也适用于这个解决方案。不可读!

于 2013-09-28T18:58:03.200 回答