C# 合并重复列表项并对它们的第二个值求和(二维对象列表)

C# Merging duplicate list items and sum their second values (2D Object List)

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

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

好吧,简单的分组应该可行:

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

这里最好使用Dictionary,检查是否包含key。所以每次你想添加新产品时只需执行以下操作

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