简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM