我想出了以下 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};
好吧,你可以把东西括起来:
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};
但是,我个人可能会将其保留为两个查询。它更清晰,不会影响性能 - 它不像代码中的第一个语句会实际执行查询。