views:

2305

answers:

3

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?

+2  A: 

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

eglasius
Could not translate expression '(...).Select(o => o.Price).Sum()' into SQL and could not treat it as a local expression.
roman m
Try itemsCard.ToList().Select(c=>c.Price).Sum();
Jonathan Parker
@rm if you are getting the info anyway, do as Jonathan mentioned (save the list on a variable, so you only get the data once).
eglasius
Jonathan - i'd accept your comment as answer .. you can post it here if you want the rep :)
roman m
@rm updated version will hit the db only once and doesn't have the issue (instead of twice as the other solutions)
eglasius
+2  A: 

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.

Jonathan Parker
you get to keep +1 :)
roman m
I need other columns for other things, that's the whole reason i didn't want to get another IQueryable< T> from the DB
roman m
+1  A: 

What about:

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

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

CMS
that's even better, thanx
roman m