gpt4 book ai didi

c# - GroupJoin() 之后的 SelectMany()

转载 作者:行者123 更新时间:2023-12-05 09:23:27 26 4
gpt4 key购买 nike

基本上,我想做的是左外连接两个表并将它们呈现在一个平面结果中。为简单起见,我的两个表如下所示:

tot["nameA", "nameB", "nameC"]
critItg["nameA", "nameB"]

我希望左外连接后的结果如下所示:

leftName, rightName
"nameA", "nameA"
"nameB", "nameB"
"nameC", empty/null

我已经设法通过以下方式执行左外连接:

var res = tot.GroupJoin
(
critITG,
left => left.totName,
right => right.critITGName,
(left, right) => new
{
tot = left,
critITG = right.FirstOrDefault()
}
);

然而,结果是这样分组的:

{ tot = { totName = "nameA" }, { critITG = "nameA"} }
{ tot = { totName = "nameB" }, { critITG = "nameB"} }
{ tot = { totName = "nameC" }, { critITG = null} }

我希望结果看起来更像这样:

{ totName = "nameA", critITG = "nameA" }

我读到过将我的左外连接结果展平的解决方案是 SelectMany(),但我在上面的结果集上实现它时遇到了问题。下面的结果集是“未设置对象实例的对象引用:

var res = tot.GroupJoin
(
critITG,
left => left.totName,
right => right.critITGName,
(left, right) => new
{
tot = left,
critITG = right.FirstOrDefault()
}
)
.SelectMany
(
right => right.critITG.critITGName.DefaultIfEmpty(),
(left, right) =>
new
{
leftName = left.tot.totName,
rightName = right
}
);

感谢您的帮助!

最佳答案

看起来您陷入了 lambda 构造的技术细节,这可能会随着时间的推移导致代码可维护性降低。通常我发现查询语法比连接的 lambda 语法更简单、更易于维护。请考虑以下事项:

var tots = new string[] {"nameA", "nameB", "nameC"};
var critItgs = new string[] {"nameA", "nameB"};

var query = from tot in tots
join critItg in critItgs on tot equals critItg into joined
from row in joined.DefaultIfEmpty()
select new {totName = tot, critItg = row};
query.Dump();

关于c# - GroupJoin() 之后的 SelectMany(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21732184/

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