Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL .Sum() without group ... into

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?

like image 546
roman m Avatar asked Mar 13 '09 06:03

roman m


3 Answers

What about:

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

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

like image 119
Christian C. Salvadó Avatar answered Oct 24 '22 06:10

Christian C. Salvadó


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 :)

like image 19
eglasius Avatar answered Oct 24 '22 05:10

eglasius


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.

like image 8
Jonathan Parker Avatar answered Oct 24 '22 06:10

Jonathan Parker