Linq to SQL .Sum() without group … into

后端 未结 5 716
名媛妹妹
名媛妹妹 2020-12-18 18:04

I have something like this:

var itemsInCart = from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select          


        
相关标签:
5条回答
  • 2020-12-18 18:14

    What about:

    itemsInCart.AsEnumerable().Sum(o=>o.Price);
    

    AsEnumerable makes the difference, this query will execute locally (Linq To Objects).

    0 讨论(0)
  • 2020-12-18 18:16

    Try:

    itemsCard.ToList().Select(c=>c.Price).Sum();
    

    Actually this would perform better:

    var itemsInCart = from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.WishListItem.Price };
    var sum = itemsCard.ToList().Select(c=>c.Price).Sum();
    

    Because you'll only be retrieving one column from the database.

    0 讨论(0)
  • 2020-12-18 18:16

    Try this:

    var itemsInCart = from o in db.OrderLineItems
                      where o.OrderId == currentOrder.OrderId
                      select o.WishListItem.Price;
    
    return Convert.ToDecimal(itemsInCart.Sum());
    

    I think it's more simple!

    0 讨论(0)
  • 2020-12-18 18:29

    you can:

    itemsCart.Select(c=>c.Price).Sum();

    To hit the db only once do:

    var itemsInCart = (from o in db.OrderLineItems
                      where o.OrderId == currentOrder.OrderId
                      select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                      ).ToList();
    var sum = itemsCart.Select(c=>c.Price).Sum();
    

    The extra round-trip saved is worth it :)

    0 讨论(0)
  • 2020-12-18 18:35

    I know this is an old question but why can't you do it like:

    db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);
    

    I am not sure how to do this using query expressions.

    0 讨论(0)
提交回复
热议问题