我有一个简单的linq查询,我需要在一定距离内过滤商店,并按距离计算结果排序,你明白了。
所以,我最后两次调用GetDistance方法。如何优化代码以便每个商店只调用一次?
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();
答案 0 :(得分:13)
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();
答案 1 :(得分:13)
相当于Yuriy的答案,有些人(我)更容易阅读:
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();
编译器只是将其转换为看起来很像Yuriy代码的代码。