如何将TotalSum设置为列表中所有LineSum的总计?
这是一个购物车,我需要计算列表中每个项目的总和(产品价格*数量),以及购物车的总计(lineSum1 + lineSum2 + lineSum3等等)< / p>
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;
}
}
}
答案 0 :(得分:3)
使用带有选择器的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;
}