所以,基本上我已經創建了一個物件實體并在其中添加了專案:
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
uj5u.com熱心網友回復:
好吧,簡單的 group by 應該可以作業:
liste1
.GroupBy(x => x.Barcode)
.Select(g => new Product()
{
Barcode = g.Key,
Quantity = g.Select(x => x.Quantity).Sum()
});
uj5u.com熱心網友回復:
最好在這里使用 Dictionary 并檢查包含鍵。所以每次你想添加新產品時,只需執行以下操作
if (dictionary.ContainsKey("product"))
{
dictionary["product"] = dictionary["product"] quantity;
}else{
dictionary.Add("product", quantity);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/337393.html
