通过LINQ选择十进制值

who*_*ee1 3 .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;
        }        
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*zek 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();
Run Code Online (Sandbox Code Playgroud)

如果查询有可能返回多于一个或零元素使用First()/ FirstOrDefault()而不是.