【问题标题】:Calculate sum of multiple items in array in C#在C#中计算数组中多项的总和
【发布时间】:2014-04-15 16:27:35
【问题描述】:

我正在尝试为我在班级中的项目获得总和。为了更好地解释你,我有购物车对象,我可以用这种方法计算总和:

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

我们例子中的 item 对象是这个:

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

最后一个属性,Modifiers 是我今天添加的新属性,内容如下:

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

我想要实现的是当调用 ComputeTotalValue 时,如果还有 ModifierOption 字段,我也想计算这些字段的总和并将结果包含在总和中。

【问题讨论】:

    标签: c# asp.net linq linq-to-entities


    【解决方案1】:

    您可以将修饰符的价格添加到您的物品价格中,不是吗?

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

    【讨论】:

    • 如果某些项目我有 null 怎么办?
    • 那么检查是否为空!并按照您认为正确的方式处理它们。我只提供了基本解决方案 - 如果需要,您可以扩展它
    【解决方案2】:

    这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多