如何从DataTable和LINQ获取分组的字段数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从DataTable和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);

从这张表我想只有values分组的key

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

我如何只选择value

答案

对于每个nGroup,您需要选择values:

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

以上是关于如何从DataTable和LINQ获取分组的字段数组的主要内容,如果未能解决你的问题,请参考以下文章