简体   繁体   English

如何将Linq Group By和Foreach语句重构为一个Linq查询

[英]How to refactor Linq Group By and Foreach statement into one Linq Query

I am having some trouble trying to refactor the LINQ query below into one single query: 我在尝试将下面的LINQ查询重构为一个查询时遇到一些麻烦:

// produces 8 results
            var qryResults =
                (from r in dbContext.Routes
                 join br in dbContext.BrokerRoutes on r.RouteId equals br.RouteId
                 join pr in dbContext.RoutePathFilters.Include(x => x.PathFilter) on r.RouteId equals pr.RouteId into paths
                 where br.Broker.ApiKey == apiKey
                 select new RouteTemplate
                    {
                        RouteId = r.RouteId,
                        Version = r.Version.Version,
                        Url = r.Url,
                        IsActive = r.IsActive,
                        Paths = paths.Select(x => x.PathFilter.FilterName).ToList()
                 })
                .AsNoTracking()
                .ToImmutableList();
// takes 8 results and turns that into 2 overall objects.
            var results = new List<RouteTemplate>();
            foreach (var r in qryResults)
            {
                if (results.All(x => x.RouteId != r.RouteId))
                {
                    r.Paths = qryResults
                        .Where(x => x.RouteId == r.RouteId)
                        .Select(x => x.Paths.First()).ToList();
                    results.Add(r);
                }
            }

r is duplicated by each value held in the paths property. rpaths属性中保存的每个值复制。

I know that foreach can be combined into the linq query above but i have been trying for a few hours now. 我知道foreach可以合并到上面的linq查询中,但是我已经尝试了几个小时。 So i am interesting know if it possible or not and how can it be done ? 所以我很有趣地知道它是否可行以及如何完成?

Without the actual database, I am not sure if this will work, but here is my attempt: 没有实际的数据库,我不确定是否能正常工作,但这是我的尝试:

var qryResults =
    (from r in dbContext.Routes
     join br in dbContext.BrokerRoutes on r.RouteId equals br.RouteId
     where br.Broker.ApiKey == apiKey
     join pr in dbContext.RoutePathFilters.Include(x => x.PathFilter) on r.RouteId equals pr.RouteId into paths
     group new { r, paths } by r.RouteId into rprg
     let r = rprg.First().r
     select new RouteTemplate {
         RouteId = rprg.Key,
         Version = r.Version.Version,
         Url = r.Url,
         IsActive = r.IsActive,
         Paths = rprg.Select(rpr => rpr.paths.First().PathFilter.FilterName).ToList()
     })
    .AsNoTracking()
    .ToImmutableList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM