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

时间:2019-03-01 12:19:13

标签: c# linq linq-to-entities entity-framework-core

尝试将下面的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);
                }
            }

rpaths属性中保存的每个值重复。

我知道foreach可以合并到上面的linq查询中,但是我已经尝试了几个小时。所以我很有趣,知道是否可能以及如何完成?

1 个答案:

答案 0 :(得分:1)

没有实际的数据库,我不确定这是否行得通,但这是我的尝试:

double