簡體   English   中英

用C#計算數組中多項的總和

[英]Calculate sum of multiple items in array in C#

我正在嘗試為我在課堂上擁有的項目求總和。 為了更好地向您解釋,我有一個購物車對象,我可以使用此方法計算總和:

 public decimal ComputeTotalValue()
        {
            return itemCollection.Sum(e => e.Item.Price*e.Quantity);                        
        }

我們案例中的項目對象是這樣的:

public class CartItem
        {
            public RestItem Item { get; set; }
            public int Quantity { get; set; }
        }

現在 RestItem 類具有以下屬性:

public class RestItem
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int InStockNow { get; set; }
        public int Order { get; set; }
        public decimal Price { get; set; }
        public bool HasImage { get; set; }
        public bool HasModifiers { get; set; }
        public string PLU { get; set; }
        public int CategoryId { get; set; }
        public byte[] ImageArray { get; set; }
        public IEnumerable<ModifierOption> Modifiers { get; set; }
    }

最后一個屬性,修飾符是我今天包含的新屬性,這是內容:

public class ModifierOption
    {
        public string ID { get; set; }
        public decimal Price { get; set; }            
    }

我想要實現的是在調用 ComputeTotalValue 時,如果還有 ModifierOption 字段,我也想計算這些字段的總和並將結果包含在總和中。

您可以將修改器的價格添加到您的物品價格中,不是嗎?

public decimal ComputeTotalValue()
{
   return itemCollection.Sum(e => (e.Item.Price + e.Item.Modifiers.Sum(m=>m.Price))*e.Quantity);                        
}

像這樣做:

public class RestItem
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int InStockNow { get; set; }
    public int Order { get; set; }
    public decimal Price { get; set; }
    public bool HasImage { get; set; }
    public bool HasModifiers { get; set; }
    public string PLU { get; set; }
    public int CategoryId { get; set; }
    public byte[] ImageArray { get; set; }
    public IEnumerable<ModifierOption> Modifiers { get; set; }

    public decimal ComputeTotalPrice() {
        return (this.Modifiers?.Sum(x => x.Price) ?? 0) + Price;
    }
}

public decimal ComputeTotalPrice(){ 
    return itemCollection?.Sum(x => x.ComputeTotalPrice()) ?? 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM