I have something like this:
var itemsInCart = from o in db.OrderLineItems
where o.OrderId == currentOrder.OrderId
select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
is there any way to do a
itemsCart.Sum() //not sure what to pass into the function
to get the sum of o.WishListItem.Price or do i have to get another iQueryable< T> from the database with group ... into?
What about:
itemsInCart.AsEnumerable().Sum(o=>o.Price);
AsEnumerable makes the difference, this query will execute locally (Linq To Objects).
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With