C# define LET in LINQ

10,413

There is an easy way to pre-compile LINQ Queries:

var distanceToFirstFromMe =
    CompiledQuery.Compile<Route, GeoCoordinates, Distance>((route, currentLocation) => {
        return route.coordinates
            .Select(c => c.position)
            .FirstOrDefault()
            .Distance(DbGeography.FromText(currentLocation, 4326));
    });

To use them in your query, you can simply call them:

IQueryable<RouteQueryModel> query =
    (from b in db.routes
     let avg_rating = b.ratings.Any() ? 
         b.ratings.Select(r => r.rating1).Average() : 0
     let distance_to_first_from_me = distanceToFirstFromMe(b, currentLocation)
     // ...
Share:
10,413
Lord Vermillion
Author by

Lord Vermillion

Updated on June 14, 2022

Comments

  • Lord Vermillion
    Lord Vermillion almost 2 years

    I have multiple LINQ queries that uses the same LET variables, I would like to predefine these somehow.

    IQueryable<RouteQueryModel> query =
        (from b in db.routes
         let avg_rating = b.ratings.Any() ? 
             b.ratings.Select(r => r.rating1).Average() : 
             0
         let distance_to_first_from_me = b.coordinates.
             Select(c => c.position).
             FirstOrDefault().
             Distance(DbGeography.FromText(currentLocation, 4326))
         let distance_to_last_from_me = b.coordinates.
             OrderByDescending(c => c.sequence).
             Select(d => d.position).
             FirstOrDefault().
             Distance(DbGeography.FromText(currentLocation, 4326))
         let distance_to_from_me = distance_to_first_from_me < distance_to_last_from_me ? 
             distance_to_first_from_me : 
             distance_to_last_from_me
         where b.endpoints.Any(e => values.Any(t => t == e.town.town_id))
         select new RouteQueryModel 
         { 
             b = b, 
             distance_to_from_me = distance_to_from_me.Value, 
             avg_rating = avg_rating
         }
     );
    

    I'm using those three distance_to LETs in 8 different queries, is there any way to make a template for those that i can use in my queries?