如何使用 LINQ 从 DataTable 中获取分组的字段数组

How to get grouped array of fields from DataTable with LINQ

我有一个DataTable

var tbl = new DataTable();
tbl.Columns.Add("key",typeof(int));
tbl.Columns.Add("value",typeof(int));
tbl.Rows.Add(1, 2);
tbl.Rows.Add(1, 4);
tbl.Rows.Add(3, 6);
tbl.Rows.Add(3, 8);
tbl.Rows.Add(3, 10);

从这个 table 我只想 valueskey 分组,例如

{{2,4},{6,8,10}} 

更准确地说是IEnumerable<IEnumerable<int>>

我设计了一个查询

var res = from row in tbl.AsEnumerable() 
           group row by row.Field<int>("key") 
           into nGroup  select nGroup;

这给了我 DataRowkey 组合的组,即 IEnumerable<IGrouping<int, DataRow>>.

如何才能 select value

对于每个 nGroup,您需要 select value

var res = from row in tbl.AsEnumerable()
          group row by row.Field<int>("key") into nGroup
          select (
              from n in nGroup
              select n.Field<int>("value")
          );