问题描述
如何使用 lambda 表达式将此 linq 查询重写为实体?
我想在我的 lambda 表达式中使用 let 关键字或等效关键字.
How can I rewrite this linq query to Entity on with lambda expression?
I want to use let keyword or an equivalent in my lambda expression.
var results = from store in Stores
let AveragePrice = store.Sales.Average(s => s.Price)
where AveragePrice < 500 && AveragePrice > 250
对于一些类似的问题,比如我的问题下的评论,建议
For some similar questions like what is commented under my question, it's suggested to
.Select(store=> new { AveragePrice = store.Sales.Average(s => s.Price), store})
这将计算每个项目的平均价格,而在我提到的查询样式中,let 表达式阻止多次计算平均值.
which will calculate AveragePrice for each item, while in Query style I mentioned, let expression prevents to calculate average many times.
推荐答案
因此,您可以使用扩展方法语法,这将比您当前使用的多一个 lambda 表达式.没有 let
,您只需使用多行 lambda 并声明一个变量:
So, you can use the extension method syntax, which would involve one lambda expression more than you are currently using. There is no let
, you just use a multi-line lambda and declare a variable:
var results = Stores.Where(store =>
{
var averagePrice = store.Sales.Average(s => s.Price);
return averagePrice > 250 && averagePrice < 500;
});
请注意,我更改了平均价格比较,因为您的结果永远不会返回任何结果(大于 500 且小于 250).
Note that I changed the average price comparison, because yours would never return any results (more than 500 AND less that 250).
替代方案是
var results = Stores.Select(store => new { Store = store, AveragePrice = store.Sales.Average(s => s.Price})
.Where(x => x.AveragePrice > 250 && x.AveragePrice < 500)
.Select(x => x.Store);
这篇关于如何“让"在 lambda 表达式中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!