以下查询确实解决了我的问题,但它似乎过于复杂.
问题是我有一个存储菜单选项(id,名称,描述和价格)的表.我还有一个会话变量,用于存储字典中的用户选择(存储id和数量).
我在下面制作的LINQ基本上计算了总结的一切的价值.它将表转换为字典,然后将价格乘以数量.
有一个更好的方法吗?
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]);
Run Code Online (Sandbox Code Playgroud)
该select部分是不必要的,可以删除:
var prices = _db.MenuOptions.ToDictionary(o => o.Id, o => o.Price);
Run Code Online (Sandbox Code Playgroud)
计算price可以从orderItems:
Session["price"] = orderItems.Sum(oi => oi.Value * prices[oi.Key]);
Run Code Online (Sandbox Code Playgroud)
(假设所有orderItems在数据库中都有价格。)
编辑:从 Arcturus 的答案来看,这样的事情对于“one-liner”来说也可能是可能的,但可能会慢一些(参见评论):
Session["price"] = orderItems.Sum(oi => oi.Value * _db.MenuOptions.Single(o => o.ID == oi.Key).Price);
Run Code Online (Sandbox Code Playgroud)