LINQ具有分组和求和功能

时间:2014-10-03 18:26:26

标签: c# linq

我需要对deptneedWeek进行分组,然后将sum加在一起,将open加在一起,然后将closed加在一起。

此查询:

var query8 = from q8 in query7
             group q8 by new { q8.q7.dept, q8.needWeek, q8.q7.allCount, q8.q7.openCount, q8.q7.closedCount } into g
             select new
             {
                 dept = g.Key.dept,
                 needWeek = g.Key.needWeek,
                 sum = g.Sum(q8 => g.Key.allCount),
                 open = g.Sum(q8 => g.Key.openCount),
                 closed = g.Sum(q8 => g.Key.closedCount)
             };

将返回:

{ dept = foo, needWeek = 05/20/12, sum = 7, open = 3, closed = 4 }
{ dept = foo, needWeek = 05/20/12, sum = 2, open = 0, closed = 2 }

但我需要:

{ dept = foo, needWeek = 05/20/12, sum = 9, open = 3, closed = 6 }

我有多接近?

2 个答案:

答案 0 :(得分:2)

你很接近,但你正在按所有不必要的字段进行分组。只需按所有人共同的方式进行分组。

var query8 =
    from q8 in query7
    group new { q8.q7.allCount, q8.q7.openCount, q8.q7.closedCount }
       by new { q8.q7.dept, q8.needWeek }
       into g
    select new
    {
        g.Key.dept,
        g.Key.needWeek,
        sum = g.Sum(x => x.allCount),
        open = g.Sum(x => x.openCount),
        closed = g.Sum(x => x.closedCount),
    };

答案 1 :(得分:0)

  

我需要对deptneedWeek

进行分组

那么为什么您的代码不符合您的需求呢?为什么要按一切分组?

group q8 by new { q8.q7.dept, q8.needWeek } into g
select new
{
    dept = g.Key.dept,
    needWeek = g.Key.needWeek,
    sum = g.Sum(q8 => g.q7.allCount),
    open = g.Sum(q8 => g.q7.openCount),
    closed = g.Sum(q8 => g.q7.closedCount)
};