Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve my LINQ

Tags:

c#

linq

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]);
like image 490
Matt Avatar asked Mar 07 '14 10:03

Matt


1 Answers

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);
like image 197
Raidri Avatar answered Sep 19 '22 23:09

Raidri