我有以下代码:
public ViewResult Stock(Guid id)
{
// Get the product form the database
var product = productRepository.GetById(id);
var viewModel = new ProductStockViewModel()
{
Product = product,
ProductStoreStock = storeDB.Stores.Select(store => new ProductStoreStockViewModel()
{
Store = store,
Bought = storeDB.Stocks
.Where(s => s.StoreId == store.StoreId)
.Where(p => p.ProductId == product.ProductId)
.Sum(s => s.Quantity),
Sold = storeDB.OrderDetails
.Where(o => o.Order.StoreId == store.StoreId)
.Where(o => o.ProductId == product.ProductId)
.Sum(s => s.Quantity)
})
.ToList()
};
return View(viewModel);
}
public class ProductStoreStockViewModel
{
public Store Store { get; set; }
//public Product Product { get; set; }
public decimal Bought = 0;
public decimal Sold = 0;
public decimal Stock
{
get { return Bought - Sold; }
}
}
我理解错误,有时产品已售出 0 次,因此 .Sum(s => s.Quantity) 返回空值。我知道我可以使用??0 如果满足该条件,但在 Linq 方法语法中表达该条件的最优雅方式是什么?