如何“让”在lambda表达式? [英] How to "let" in lambda expression?

查看:188
本文介绍了如何“让”在lambda表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用lambda表达式将此linq查询重写为Entity?

我要在我的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})

这将计算每个项目的AveragePrice,而在我提到的查询风格中,表达式阻止计算平均次数。

which will calculate AveragePrice for each item, while in Query style I mentioned, let expression prevents to calculate average many times.

推荐答案

因此,可以使用扩展方法语法,比你目前正在使用。没有 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;
});

请注意,我更改了平均价格比较,因为您的数据永远不会返回任何结果

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表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆