使用LINQ的GroupBy列

时间:2018-12-24 15:36:59

标签: c# .net linq

我想使用followng方法按数据表分组。但是我无法选择包含字符串的列

var dtTAConvertList =
    (from dr1 in dtTAConvert.AsEnumerable()
     group dr1 by dr1.Field<DateTime>("SAMPLE_TIME") into g
     select new
     {
         SAMPLE_TIME = g.Key,
         WAIT_CLASS = g.Field<string>("WAIT_CLASS"),          // ==> I get error in this line
         COUNT = Math.Round(g.Sum(h => h.Field<double>("COUNT")) / 15.0, 2),
     });

它引发异常

  

'IGrouping'不包含'Field'的定义,最佳扩展方法重载'DataRowExtensions.Field(DataRow,string)'需要类型为'DataRow'的接收器

如何选择该数据表中已经存在的字符串列?

1 个答案:

答案 0 :(得分:2)

由于每个组中Field<string>("WAIT_CLASS")的出现次数很多,因此除了可能要检索第一个出现次数之外,您将必须执行与计数相同的方法:

var dtTAConvertList =
    (from dr1 in dtTAConvert.AsEnumerable()
     group dr1 by dr1.Field<DateTime>("SAMPLE_TIME") into g
     select new {
         SAMPLE_TIME = g.Key,
         WAIT_CLASS = g.First().Field<string>("WAIT_CLASS"),
         COUNT = Math.Round(g.Sum(h => h.Field<double>("COUNT")) / 15.0, 2),
     });