我有所有Purches
物品清單
我想將新專案添加到我的串列中,將串列中的所有專案相加
這是我的代碼:
public class Purches
{
public int Id { get; set; }
public int Items { get; set; }
public int TotalPrice { get; set; }
}
List<Purches> purchesList = new List<Purches>() {
new Purches() {
Id = 1,
Items = 3,
TotalPrice = 220
},
new Purches() {
Id = 2,
Items = 5,
TotalPrice = 300
}
};
現在,我想添加匯總Items
和TotalPrice
屬性的串列新專案
結果將是這樣的:
List<Purches> purchesList = new List<Purches>() {
new Purches() {
Id = 1,
Items = 3,
TotalPrice = 220
},
new Purches()
{
Id = 2,
Items = 5,
TotalPrice = 300
},
new Purches()
{
Id = 0,
Items = 8,
TotalPrice = 550
}
};
我必須通過 C# 中的 linq / Lambda 來完成
uj5u.com熱心網友回復:
Purches totalSum = new Purches
{
Id = 0,
Items = purchesList.Sum(p => p.Items),
TotalPrices = purchesList.Sum(p => p.TotalPrices)
};
// now add it to your list if desired
uj5u.com熱心網友回復:
我不建議添加相同型別的摘要項。這很可能會導致混亂。更好的解決方案是使用單獨的物件作為總數,或者使用具有共享介面的不同型別,例如:
public class PurchaceSummary{
public List<Purches> Purchases {get;}
public TotalItemCount => Items.Sum(p => p.Items);
public TotalPrice => Items.Sum(p => p.TotalPrices);
}
或者
public interface IPurchaseLineItem{
public int Items { get; }
public int TotalPrice { get; }
}
public interface Purchase : IPurchaseLineItem{
public int Id { get; set; }
public int Items { get; set; }
public int TotalPrice { get; set; }
}
public interface PurchaseSummary : IPurchaseLineItem{
public int Items { get; set; }
public int TotalPrice { get; set; }
}
// Use the LINQ methods from the previous example to create your totals for the summary
在任何一種情況下,每個人都應該立即清楚每個值代表什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510656.html
標籤:C#林克拉姆达