I need help in getting the total quantity for each item persisted to the OrderDetail table in the DB.
Given the following:-
List
usersShoppingCart.SubmitOrder(User.Identity.Name, out orderDetails);
foreach(OrderDetail od in orderDetails)
{
int quantity = od.Quantity;
}
The quantity variable only holds 1 quantity at a time rather than the total quantity.
For example if I had 2 items in my cart, both with quanitities of 1, only 1 quantity will get stored in the quantity variable but I would like 2, 1 per item.
Any help in achieving this would be great.
Thanks
Steven
VulpesPosted May 8, 2012, 11:19 AM
VulpesPosted May 10, 2012, 12:06 PM
int totalQuantity = orderDetails.Select(od => od.Quantity).Sum();
That's because the iteration is already implied by the Select() method which looks at each element of the orderDetails list in turn, extracts its Quantitiy property and sums them.
However, more generally, you'll get that sort of error if you try to use a local variable which is already defined in an enclosing scope. That happens here because the variable 'od' which is local to the lambda expression is within the scope of the foreach statement which is also using 'od' as an iteration variable. This is regarded as an error because there would be no way to access the 'od' variable in the outer scope.
Guest UserPosted May 10, 2012, 11:52 AM
Quick one please, given:-
foreach (OrderDetail od in orderDetails)
{
int totalQuantity = orderDetails.Select(od => od.Quantity).Sum();
}
An error of "A local variable named 'od' cannot be declared in this scope because it would give a different meaning to 'od', which is already used in a 'parent or current' scope to denote something else.
The error is occurring on the first 'od' after Select?
Thanks
Steven
Guest UserPosted May 8, 2012, 11:37 AM