如何在视图模型中设置总计 属性 的值

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

如何将 TotalSum 设置为列表中所有 LineSums 的总和?

这是一个购物车,我需要计算列表中每个项目的总和(产品价格*数量),以及购物车的总计(lineSum1+lineSum2+lineSum3,等等... )

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

使用带选择器的overload of Sum

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

您还必须修复 ViewModelShoppingCartItem.LineSum-属性:

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