通过LINQ选择十进制值

时间:2012-04-02 04:35:27

标签: .net linq entity-framework linq-to-sql

我试图在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;
        }        
    }

2 个答案:

答案 0 :(得分:5)

如果您的查询始终只返回一个值,请使用.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()

答案 1 :(得分:3)

该错误消息表明cartItems.Product.aWeekPrice是一个集合,而不是单个集合。因此,您只需选择所需的项目即可。例如:

decimal threeDayPrice = (from cartItems in db.Cart
                     where cartItems.cartId == ShoppingCartId
                     select (decimal)cartItems.Product.threeDayPrice).FirstOrDefault();

应该删除错误消息,但是它会通过选择“threeDayPrice”字段中的第一项来实现。