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

C# 如何合并Product列表重复项并对Quantity属性值求和

实现方案1:使用LINQ分组聚合(最简洁)

首先需要引入LINQ命名空间:
using System.Linq;

直接对原列表做分组聚合即可:

List<Product> mergedList = liste1
    .GroupBy(product => product.Barcode)
    .Select(group => new Product(
        barcode: group.Key, 
        quantity: group.Sum(item => item.Quantity)
    ))
    .ToList();

逻辑说明:

  • 先按Barcode属性对所有元素分组,相同条码的元素会被归入同一组
  • 对每个分组的Quantity属性求和,用分组的Key(即条码值)和求和结果实例化新的Product对象
  • 最终转换为List类型得到合并后的列表

实现方案2:使用字典遍历实现(无需依赖LINQ,性能更优)

如果项目不能用LINQ或者要处理超大量数据,可以用字典做中间计数:

Dictionary<string, int> quantityCounter = new Dictionary<string, int>();

// 遍历原列表累加计数
foreach (Product product in liste1)
{
    if (quantityCounter.ContainsKey(product.Barcode))
    {
        quantityCounter[product.Barcode] += product.Quantity;
    }
    else
    {
        quantityCounter[product.Barcode] = product.Quantity;
    }
}

// 转换为合并后的Product列表
List<Product> mergedList = new List<Product>();
foreach (var kvp in quantityCounter)
{
    mergedList.Add(new Product(kvp.Key, kvp.Value));
}

两种方案最终得到的mergedList就是你需要的合并去重、数量求和后的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:06:04