Frage

This is 2D array:

int[][] array2D = new int[7][];
for (int i = 0; i < 7; i++)
    array2D[i] = new int[7];

How can I turn the following into a LINQ query, or use enumerable methods to achieve the same output?

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

EDIT - Solution based on @'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();
War es hilfreich?

Lösung

Try this:

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

Andere Tipps

The trick is to use the Select and SelectMany that capture the loop variables into an anonymous type, then get those properties back later after the Where clause, thus:

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

EDIT: Bartosz's comment applies to this solution as well. Unreadable!

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

However, your current solution is more readable.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top