tags:

views:

75

answers:

4

How can I use linq in C# to select the columns of a jagged array of ints, I select the rows as follows.

int[][] values;
....
var rows = from row in values select row;

Thank you for the help.

+1  A: 
var cols = values.SelectMany(v=>v.Select(c=>c))
Gregoire
It seems to me this flattens the array, is there a way to get the columns as arrays?
CoGo
+1  A: 

Add one more line:

int[][] values;
....
var rows = from row in values select row;
var cols = rows.SelectMany(x => x);
Keltex
It seems to me this flattens the array, is there a way to get the columns as arrays?
CoGo
A: 

you can also do it like this:

        int[][] values = new int[5][];
        values[0] = new int[5] { 1, 2, 3, 4, 5 };
        values[1] = new int[5] { 1, 2, 3, 4, 5 };
        values[2] = new int[5] { 1, 2, 3, 4, 5 };
        values[3] = new int[5] { 1, 2, 3, 4, 5 };
        values[4] = new int[5] { 1, 2, 3, 4, 5 };

        var rows = from r in values where r[0] == 1 select r[0];

        //two options here for navigating each row or navigating one row

        var rows = from r in values[0] where r == 1 select r;
BuildStarted
A: 
IEnumerable<IEnumerable<int>> columns = values
  .SelectMany((row, ri) => row
    .Select((x, ci) => new {cell = x, ci, ri}))
  .GroupBy(z => z.ci)
  .Select(g => g.Select(z => z.cell));

Some notes:

  • this doesn't preserve empty space from different sized arrays (remember - jagged).
  • rowindex (ri) isn't used and could be removed.
  • rowindex could be used to generate values for emptyspace if needed
David B