Select decimal value via LINQ
I am trying to get the decimal value using LINQ in an MVC3 project.
How can I get it? it looks easy, but I can't get a unambiguous value that is not a list, which is Product.aWeekPrice.
How can I get a specific 3DayPrice? Once the 3DayPrice is received, it will be used in the case of a condition to provide different terms, 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;
}
}
source to share
If your query always returns only one value, use .Single()
to get it as decimal
a set of decimal places instead.
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();
If there is a chance that the query will return to more than one or null element, use First()
/ FirstOrDefault()
.
source to share
This error message indicates that cartItems.Product.aWeekPrice is a collection and not one. Thus, you just need to select the item you want. For example:
decimal threeDayPrice = (from cartItems in db.Cart
where cartItems.cartId == ShoppingCartId
select (decimal)cartItems.Product.threeDayPrice).FirstOrDefault();
should remove the error message, but it will do so by selecting the first item in the "threeDayPrice" field.
source to share