Search code examples
c#asp.net-mvc-viewmodel

How to set the value of a grand total property in a viewmodel


How can I set the TotalSum to be a grand total of all the LineSums in my List?

This is a shopping cart, and I need to calculate the sum for each item in the list (product price * quantity), and the grand total of the shopping cart (lineSum1+lineSum2+lineSum3, etc...)

public class ViewModelShoppingCart
{
    public string Title { get; set; }
    [DataType(DataType.Date)]
    public DateTime CreateDate { get; set; }
    public List<ViewModelShoppingCartItem> ShoppingCartItems { get; set; }
    public decimal TotalSum
    {
        set
        {
            // This clearly isn't working:
            TotalSum = ShoppingCartItems.Sum();
        }
    }
}

public class ViewModelShoppingCartItem
{
    public string ProductTitle { get; set; }
    public decimal ProductPrice { get; set; }
    public int Quantity { get; set; }
    public decimal LineSum
    {
        set
        {
            LineSum = ProductPrice * Quantity;
        }
    }
}

Solution

  • Use the overload of Sum that takes the selector:

    public decimal TotalSum => ShoppingCartItems.Sum(item => item.LineSum);
    

    You also have to fix the ViewModelShoppingCartItem.LineSum-property:

    public class ViewModelShoppingCartItem
    {
        // ...
        public decimal ProductPrice { get; set; }
        public int Quantity { get; set; }
        public decimal LineSum => ProductPrice * Quantity;
    }