我试图在MVC3项目中使用LINQ获取十进制值。
我如何得到它?它看起来很简单,但我无法获得一个十进制值而不是Product.aWeekPrice列表。
如何获得特定的ThreeDayPrice?在获得threeDayPrice之后,将在if条件中给出不同的条件,如下面的代码所示:
public decimal GetTotal(decimal price)
{
// Multiply product price by count of that album to get
// the current price for each of those product in the cart
// sum all product price totals to get the cart total
//In select part, I have got error, 'cannot convert type
//'System.Linq.IQueryable<decimal>' to 'decimal'
decimal threeDayPrice = (from cartItems in db.Cart
where cartItems.cartId == ShoppingCartId
select (decimal)cartItems.Product.threeDayPrice);
decimal aWeekPrice = (from cartItems in db.Cart
where cartItems.cartId == ShoppingCartId
select (decimal)cartItems.Product.aWeekPrice);
if (price == threeDayPrice)
{
decimal? total = (from cartItems in db.Cart
where cartItems.cartId == ShoppingCartId
select (int?)cartItems.count * cartItems.Product.threeDayPrice).Sum();
return total ?? decimal.Zero;
}
else if (price == aWeekPrice)
{
decimal? total = (from cartItems in db.Cart
where cartItems.cartId == ShoppingCartId
select (int?)cartItems.count * cartItems.Product.aWeekPrice).Sum();
return total ?? decimal.Zero;
}
}
最佳答案
如果查询始终只返回一个值,请使用.Single()
将其作为decimal
而不是小数的集合。
decimal threeDayPrice = (from cartItems in db.Cart
where cartItems.cartId == ShoppingCartId
select (decimal)cartItems.Product.threeDayPrice).Single();
decimal aWeekPrice = (from cartItems in db.Cart
where cartItems.cartId == ShoppingCartId
select (decimal)cartItems.Product.aWeekPrice).Single();
如果查询可能返回更多,则使用
First()
/ FirstOrDefault()
代替一个或零个元素。