LINQ分组和计数

时间:2014-10-09 18:15:37

标签: c# linq

我知道这个问题与我之前的问题类似,但我无法弄明白。

数据:

dept  needOn    status
foo   5/1/2011  closed
foo   5/1/2011  closed
foo   5/1/2011  closed
foo   5/1/2011  closed
foo   5/1/2011  open
foo   5/1/2011  open

寻找此输出:

dept  needOn    status   count
foo   5/1/2011  closed   4
foo   5/1/2011  open     2

我认为这样可行:

var query3 = from q3 in query2
             group new { q3.Status }
                by new { q3.Dept, q3.NeedOnWeek, q3.Status } into g
             select new
             {
                 dept = g.Key.Dept,
                 needOnWeek = g.Key.NeedOnWeek,
                 status = g.Key.Status,
                 count = g.Count(x => x.Status)
             };

这两个错误都适用于:count = g.Count(x => x.Status)

错误1无法将lambda表达式转换为委托类型'System.Func',因为块中的某些返回类型不能隐式转换为委托返回类型

错误2无法将类型'string'隐式转换为'bool'

感谢您的耐心和帮助。

1 个答案:

答案 0 :(得分:2)

var query3 = from q3 in query2
             group q3
                by new { q3.Dept, q3.NeedOnWeek, q3.Status } into g
             select new
             {
                 dept = g.Key.Dept,
                 needOnWeek = g.Key.NeedOnWeek,
                 status = g.Key.Status,
                 count = g.Count()
             };