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

Time:10-27

So, basically i have created an object instance and added items in it:

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);

I want to merge and remove the duplicates and sum their quantities of these objects into a new list like this:

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

instead of these:

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

CodePudding user response:

Well, simple group by should work:

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

CodePudding user response:

Its better to use Dictionary here and check contains key. so every time you want to add new product just do below

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