Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: calling the same method for Where and OrderBy only once instead of twice?

Tags:

c#

.net

linq

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();
like image 782
Easy Rider Avatar asked Jun 17 '11 22:06

Easy Rider


2 Answers

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.

like image 151
Eric Lippert Avatar answered Oct 20 '22 18:10

Eric Lippert


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();
like image 39
Yuriy Faktorovich Avatar answered Oct 20 '22 18:10

Yuriy Faktorovich