The following query does solve my problem however it seems overly complex.
The problem is I have a table that stores menu options (id, name, description and price). I also have a session variable that stores the users selections in a Dictionary (storing id and quantity).
The LINQ I've produced below basically calculates the value of everything summed up. It converts the table to a dictionary and then sums the prices multiplied by the quantity.
Is there a better way to do this?
var prices = _db.MenuOptions
.Select(o => new { o.Id, o.Price })
.ToDictionary(o => o.Id, o => o.Price);
Session["price"] = prices
.Where(p => orderItems.Keys.Contains((int)p.Key))
.Sum(p => p.Value * orderItems[p.Key]);
The select
part is unnessecary and can be dropped:
var prices = _db.MenuOptions.ToDictionary(o => o.Id, o => o.Price);
And the price
calculation could start from the orderItems
:
Session["price"] = orderItems.Sum(oi => oi.Value * prices[oi.Key]);
(Assuming all orderItems
have a price in the db.)
Edit: Going from Arcturus answer, something like this might also be possible for a "one-liner" but is probably slower (see comments):
Session["price"] = orderItems.Sum(oi => oi.Value * _db.MenuOptions.Single(o => o.ID == oi.Key).Price);
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