Linq: calling the same method for Where and OrderBy only once instead of twice?
I have a simple linq query where I need to filter stores within a certain distance and 开发者_开发问答also order by the distance calculation result, you get the idea.
So, I ended up calling GetDistance method twice for now. How can I optimize code to call it only once per store?
double distance = 50;
var result = stores.Where<MyStore>( s =>
Helper.GetDistance( lat, lon, s.Lat, s.Lon ) <= distance )
.OrderBy( s => Helper.GetDistance( lat, lon, s.Lat, s.Lon ) )
.ToList();
An equivalent to Yuriy's answer that some people (me) find easier to read is:
double maxDistance = 50;
var query = from store in stores
let storeDistance = Helper.GetDistance(lat, lon, store.lat, store.lon)
where storeDistance < maxDistance
orderby storeDistance
select store;
var result = query.ToList();
The compiler simply translates this into code that looks much like Yuriy's code.
var result = stores.Select(store =>
new
{
distance =
StoreHelper.Current.GetDistance(latitude, longitude, store.Latitude.Value, store.Longitude.Value),
store
})
.Where(a => a.distance <= distance)
.OrderBy(a => a.distance)
.Select(a => a.store)
.ToList();
精彩评论