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

如何使用Linq按客户分组并汇总订单总额?

解决Linq分组后计算客户订单总额的问题

你已经完成了按客户分组的操作,只需在分组后的Select环节中,对每个分组内的订单金额执行求和即可得到每个客户的订单总额。

修正后的完整代码

var OrderByCustumer = new[] {
    new { name = "cust1", order = 400 },
    new { name = "cust1", order = 250 },
    new { name = "cust1", order = 130 },
    new { name = "cust2", order = 30 },
    new { name = "cust3", order = 205}
};

var res = OrderByCustumer
    .GroupBy(x => x.name)
    .Select(group => new {
        CustomerName = group.Key,
        TotalOrderAmount = group.Sum(item => item.order)
    });

foreach(var item in res){
    Console.WriteLine($"客户: {item.CustomerName}, 订单总额: {item.TotalOrderAmount}");
}

关键修改说明

  • 在Select中新增TotalOrderAmount字段,通过group.Sum(item => item.order)对当前分组内的所有订单金额求和
  • 调整输出语句,同时展示客户名和对应的订单总额

输出结果

客户: cust1, 订单总额: 780
客户: cust2, 订单总额: 30
客户: cust3, 订单总额: 205

内容的提问来源于stack exchange,提问作者Abdelkader Jaafar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:10:29