I am trying to get decimal value using LINQ in a MVC3 project.
How do I get it? it looks easy question, but I cannot get single decimal value not list which is Product.aWeekPrice.
How can I get the particular threeDayPrice? After getting threeDayPrice, it will be used in if condition for giving different conditions as you can see in my code below:
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;
}
}
If your query always returns only one value use
.Single()to get it asdecimalinstead of a collection of decimals.If there is a possibility that the query will return more then one or zero elements use
First()/FirstOrDefault()instead.