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
相关产品推荐
相关产品推荐

