我有一个像这样看起来(简化)的数据库:
var reports = new[] {
new { ReportId = 1, Title = "Report A" },
new { ReportId = 2, Title = "Report B" },
};
var testCases = new[] {
new { TestId = 1, Title = "Test A" },
new { TestId = 2, Title = "Test B" },
new { TestId = 3, Title = "Test C" },
new { TestId = 4, Title = "Test D" },
new { TestId = 5, Title = "Test E" },
};
var testRuns = new[] {
new { TestId = 1, ReportId = 1 },
new { TestId = 2, ReportId = 1 },
new { TestId = 1, ReportId = 2 },
new { TestId = 2, ReportId = 2 },
new { TestId = 3, ReportId = 2 },
new { TestId = 4, ReportId = 2 },
};
因此,我希望获得一个testCases
列表,其中包含相应的reports
,即:
Test A => [Report A, Report B]
Test B => [Report A, Report B]
Test C => [Report B]
Test D => [Report B]
Test E => []
我不确定如何在SQL或LINQ中表达它。我想我需要一个组连接或左外连接,或者它被调用,但我还无法找出正确的语法。我尝试过类似的东西,但仍然错过了一部分:
var result = tests.GroupJoin(reports, t => t.TestId, ???, (t, rs) => new { Test = t, Reports = rs });
或者可能有一种完全不同的方式来制定该查询。
编辑:并非testCases
中引用testRuns
中的每个条目。
答案 0 :(得分:2)
如果你可以在没有GroupJoin的情况下生活,你可以使用2个简单连接和GroupBy
这样做:
var temp = from c in testCases
join ru in testRuns
on c.TestId equals ru.TestId into left
from l in left
join re in reports
on l.ReportId equals re.ReportId into foo
from f in foo
select new {
Test = c.Title,
Report = f
};
//Dump only in LinqPad!
temp.GroupBy(x => x.Test).Dump();
/编辑:如果您还想要空结果,则需要使用DefaultIfEmpty()
:
public class Report
{
public int ReportId { get; set; }
public string Title { get; set; }
}
public class TestCase
{
public int TestId { get; set; }
public string Title { get; set; }
}
public class TestRun
{
public int TestId { get; set; }
public int ReportId { get; set; }
}
var temp = from c in testCases
join ru in testRuns
on c.TestId equals ru.TestId into left
from l in left.DefaultIfEmpty(new TestRun())
join re in reports
on l.ReportId equals re.ReportId into foo
from f in foo.DefaultIfEmpty()
select new {
Test = c.Title,
Report = f
};
temp.Dump();
答案 1 :(得分:1)
我认为你不需要小组加入。这将为您提供所需。结果将包含测试ID以及与之关联的报告。
var result = testRuns.GroupBy(tr => tr.TestID)
.Select(t => new {
TestID = t.Key,
Reports = t.Select(r => r.ReportID).ToList()
});