简体   繁体   English

如何使用linq选择锯齿状数组的列

[英]How can I use linq to select the columns of a jagged array

How can I use linq in C# to select the columns of a jagged array of ints, I select the rows as follows. 如何在C#中使用linq来选择一个锯齿状的int数组的列,我按如下方式选择行。

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

Thank you for the help. 感谢您的帮助。

var cols = values.SelectMany(v=>v.Select(c=>c))

Add one more line: 再添一行:

int[][] values;
....
var rows = from row in values select row;
var cols = rows.SelectMany(x => x);
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(ri)未使用,可以删除。
  • rowindex could be used to generate values for emptyspace if needed 如果需要,rowindex可用于为emptyspace生成值

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM