gpt4 book ai didi

c# - 如何制定 GroupJoin() 声明

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:59 27 4
gpt4 key购买 nike

我有一个看起来(简化)如下的数据库:

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 中表达这一点。我想我需要一个 group join 或一个 left outer join 或者不管它叫什么,但我还不知道正确的语法。我试过这样的东西,但仍然遗漏了一部分:

var result = tests.GroupJoin(reports, t => t.TestId, ???, (t, rs) => new { Test = t, Reports = rs });

或者可能有一种完全不同的方式来制定该查询。

编辑:并非 testCases 中的每个条目都在 testRuns 中被引用。

最佳答案

如果您可以不用 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();

关于c# - 如何制定 GroupJoin() 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com