具有分组和求和功能的LINQ

本文关键字:功能 LINQ 求和 | 更新日期: 2023-09-27 18:25:32

我需要在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 }

我离这儿有多远?

具有分组和求和功能的LINQ

您很接近,但您正在按所有不必要的字段进行分组。只是根据所有人的共同点进行分组。

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),
    };

我需要在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)
};