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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With