You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LINQ查询中添加Group by实现按系统用户ID统计总工时

你可以在现有查询基础上添加group by分组逻辑,调用Sum方法累加工时即可,有两种常用写法:

写法1:查询表达式(和你现有语法风格一致)

var th1 = from ss in db.SystemUsers
    join t in db.Timesheets on ss.Id equals t.SystemUser
    where (t.Project == projectId && t.StartTime >= year_start && t.StartTime < year_end)
    group t by ss.Id into g
    select new
    {
        Id = g.Key,
        TotalHours = g.Sum(x => x.TotalHours)
    };

说明:用group t by ss.Id into g表示按用户ID分组,g代表当前用户ID对应的所有工时记录集合,调用Sum方法累加该组下所有TotalHours字段值即可得到单用户总工时。

写法2:方法链写法

var th1 = db.SystemUsers
    .Join(db.Timesheets, ss => ss.Id, t => t.SystemUser, (ss, t) => new { ss.Id, t })
    .Where(x => x.t.Project == projectId && x.t.StartTime >= year_start && x.t.StartTime < year_end)
    .GroupBy(x => x.Id)
    .Select(g => new 
    {
        Id = g.Key,
        TotalHours = g.Sum(x => x.t.TotalHours)
    });

注意事项

如果你的TotalHours字段允许为空,可将Sum逻辑改为g.Sum(x => x.TotalHours ?? 0),避免空值引发计算异常。

内容的提问来源于stack exchange,提问作者RJ Uy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:06:03