【问题标题】:C# Merging duplicate list items and sum their second values (2D Object List)C# 合并重复列表项并将它们的第二个值求和(2D 对象列表)
【发布时间】:2021-12-11 19:14:10
【问题描述】:

所以,基本上我已经创建了一个对象实例并在其中添加了项目:

public Product(string barcode, int quantity)
{
    Barcode = barcode;
    Quantity = quantity;
}

List<Product> liste1 = new List<Product>();

liste1.add("Barcode 1", 1);
liste1.add("Barcode 2", 1);
liste1.add("Barcode 1", 3);
liste1.add("Barcode 2", 2);

我想合并和删除重复项,并将这些对象的数量汇总到一个新列表中,如下所示:

barcode = "Barcode 1", quantity = 4
barcode = "Barcode 2", quantity = 3

而不是这些:

barcode = "Barcode 1", quantity = 1
barcode = "Barcode 2", quantity = 1
barcode = "Barcode 1", quantity = 3
barcode = "Barcode 2", quantity = 2

【问题讨论】:

  • GroupBy 应该在这里为您提供帮助。

标签: c# list merge sum duplicates


【解决方案1】:

嗯,简单的分组应该可以工作:

liste1
    .GroupBy(x => x.Barcode)
    .Select(g => new Product() 
    {
        Barcode = g.Key, 
        Quantity = g.Select(x => x.Quantity).Sum() 
    });

【讨论】:

    【解决方案2】:

    最好在这里使用字典并检查包含键。因此,每次您想添加新产品时,只需执行以下操作

    if (dictionary.ContainsKey("product"))
    {
      dictionary["product"] = dictionary["product"] + quantity;
    }else{
      dictionary.Add("product", quantity);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-02
      • 2014-01-26
      • 2021-11-12
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多