linq的groupby+sum

本文介绍了一种使用C#对商品按类型进行分组并计算各类型商品总价的方法。通过具体的代码示例展示了如何创建商品数据集,利用LINQ对这些数据进行分组,并计算每组商品的价格总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:计算出每个商品类型的价格总和
最终结果:
类型:{ goodType = 衣物 },总价格:600
类型:{ goodType = 电子 },总价格:900
类型:{ goodType = 废品 },总价格:600

class sku_location
{
    public string goodType { get; set; }
    public string goodName { get; set; }
    public int price { get; set; }
    public int sum { get; set; }
}
static void Main(string[] args)
{
    List<sku_location> datas = new List<sku_location>();
    datas.Add(new sku_location { goodType = "衣物", goodName = "衣物1", price = 100 });
    datas.Add(new sku_location { goodType = "衣物", goodName = "衣物2", price = 200 });
    datas.Add(new sku_location { goodType = "衣物", goodName = "衣物3", price = 300 });
    datas.Add(new sku_location { goodType = "电子", goodName = "电子1", price = 400 });
    datas.Add(new sku_location { goodType = "电子", goodName = "电子2", price = 500 });
    datas.Add(new sku_location { goodType = "废品", goodName = "废品1", price = 600 });

    var responseData = datas
        .GroupBy(a => new { a.goodType })
        .Select(sku => new { goodType = sku.Key, sum = sku.Sum(s => s.price) }).ToList();
    for (int i = 0; i < responseData.Count; i++)
    {
        Console.WriteLine("类型:" + responseData[i].goodType + ",总价格:" + responseData[i].sum);
    }
    Console.ReadKey();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星银色飞行船

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值