2

我有多个使用相同 LET 变量的 LINQ 查询,我想以某种方式预定义这些查询。

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
     }
 );

我在 8 个不同的查询中使用这三个 distance_to LET,有没有办法为我可以在查询中使用的模板制作模板?

4

1 回答 1

5

有一种预编译 LINQ 查询的简单方法:

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

要在查询中使用它们,您可以简单地调用它们:

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)
     // ...
于 2013-03-18T09:58:06.583 回答