Take the 2-minute tour ×

This is 2D array:

int[][] array2D = new int[7][];
    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();
share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

Try this:

var lst = array2D.SelectMany((x,r) => x.Select((a,c)=> new {a,b=new Point(c,r)})
share|improve this answer
This won't work: the c loop variable operates on the filtered row, and won't reflect the indices of the original array. –  CSJ Sep 28 '13 at 18:59
@CSJ you're right, a little mistake. –  King King Sep 28 '13 at 19:02
Lots of edits, but you got it right finally :) This is the most compact answer. I like this. –  Nayan Sep 28 '13 at 19:03
Can you please use better var names? :) –  Nayan Sep 28 '13 at 19:04
@Nayan the r and c follow your original code, I don't have any idea for other mediate var names. –  King King Sep 28 '13 at 19:05
show 4 more comments

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

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

share|improve this answer
Your solution gives almost right answer... actually, you swapped x and y. So, the list contains 'Point(y, x)' data. Numeric values are correct, though. –  Nayan Sep 28 '13 at 19:08
I think LINQ is something unreadable in many cases. The more complex the query is, the more unreadable we can feel, maybe that's because of it's succinctness. –  King King Sep 28 '13 at 19:12
add comment
var lst = array2D
    .SelectMany((innerArray, r)
        => Enumerable
               .Range(0, innerArray.Length)
               .Where(c => innerArray[c] == 0)
               .Select(c => new Point(c, r)))

However, your current solution is more readable.

share|improve this answer
Your first answer works, but second isn't compilable as Point is structure, not a class. So, you can't type cast a null to Point. Thanks! –  Nayan Sep 28 '13 at 19:13
@Nayan Right. I've removed the wrong version. –  BartoszKP Sep 28 '13 at 19:33
add comment

Your Answer


