In a lambda expression, how do you "let"?

c#-4.0 entity-framework lambda let linq


How can I adapt this Linq query to use a lambda expression on an Entity?
In my lambda expression, I want to utilize the let term or something similar.

var results = from store in Stores
              let AveragePrice =  store.Sales.Average(s => s.Price)
              where AveragePrice < 500 && AveragePrice > 250

For certain queries like the ones that were remarked on under mine, it is advised to

.Select(store=> new { AveragePrice = store.Sales.Average(s => s.Price), store})

This will compute AveragePrice for each item, however the let statement in the Query style I specified precludes calculating the average more than once.

2/11/2012 2:29:56 PM

Accepted Answer

In order to utilize the extension method syntax, you would need one more lambda expression than you need right now. There doesn'tlet , all you have to do is define a variable and use a multi-line lambda:

var results = Stores.Where(store => 
    var averagePrice = store.Sales.Average(s => s.Price);
    return averagePrice > 250 && averagePrice < 500;

Given that yours will never provide any results, please take note that I adjusted the average price comparison (more than 500 AND less that 250).

The substitute is

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);
2/11/2012 1:09:15 PM

Popular Answer

Basically, you must add the average to your object using Select and an anonymous type before continuing with the remainder of your statement.

Not tested, but it ought to appear as follows:

x => new { averagePrice = x.Sales.Average(s => s.Price), store = x})
.Where(y => y.averagePrice > 500 && y.averagePrice < 250)
.Select(x =>;

Be cautious while using these constructions, please. When dealing with big collections, let uses a lot of memory since it produces a new anonymous type for each item in the collection.

Details may be found here: chained extension methods into the mix.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow