簡體   English   中英

C#在LINQ中定義LET

[英]C# define LET in LINQ

我有多個使用相同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 LETs,有什么辦法為我可以在查詢中使用的模板制作模板嗎?

有一個簡單的方法可以預編譯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)
     // ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM