Linq和三个表分组

时间:2012-06-21 11:02:28

标签: linq join linq-group

我已经提出了以下LINQ,但我不禁想到我应该能够在一个查询而不是两个查询中执行此操作。有人可以帮忙吗?

这个想法是内连接三个表并逐个组合。

var q1 = from er in ExportRules
    join per in PlaceExportRules on er.ExportRulesID equals per.ExportRulesID
    select new 
    {
        PlaceID = per.PlaceID, 
        Description = er.Description, 
        Tag = er.TagName,
        ExportName = per.ExportName,
        ExportAddress = per.ExportAddress
    };

var q2 = from p in Places 
    join rules in q1 on p.PlaceID equals rules.PlaceID into joined2
    where joined2.Any()
    orderby p.PlaceName
    select new {Place = new {p.PlaceID, p.PlaceName}, joined2};

1 个答案:

答案 0 :(得分:2)

嗯,你可以把事情包括起来:

var query = from p in Places
            join rules from 
                 (from er in ExportRules
                  join per in PlaceExportRules 
                    on er.ExportRulesID equals per.ExportRulesID
                  ...)
              on p.PlaceId equals rules.PlaceId into joined2
            where joined2.Any()
            orderby p.PlaceName
            select new {Place = new {p.PlaceID, p.PlaceName}, joined2};

但是,我个人可能会把它留作两个查询。它更清晰,不会影响性能 - 它不像代码中的第一个语句实际上执行查询。