gpt4 book ai didi

.net - 通过 LINQ 选择十进制值

转载 作者:行者123 更新时间:2023-12-01 01:26:15 25 4
gpt4 key购买 nike

我正在尝试在 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()而是。

关于.net - 通过 LINQ 选择十进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com