I have something like this:
var itemsInCart = from o in db.OrderLineItems
where o.OrderId == currentOrder.OrderId
select
What about:
itemsInCart.AsEnumerable().Sum(o=>o.Price);
AsEnumerable makes the difference, this query will execute locally (Linq To Objects).
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.
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!
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 :)
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.