gpt4 book ai didi

c# - LINQ 右连接和左连接

转载 作者:行者123 更新时间:2023-11-30 14:09:47 25 4
gpt4 key购买 nike

我的任务是将一些 t-sql 查询重构为 LINQ。简单连接和左外连接很清楚。这是我的代码:

string[] leftouter = new string[] { "a", "b", "c", "d", "e" };
string[] inner = new string[] { "a", "b" };

var q = from s1 in leftouter
join s2 in inner on s1 equals s2 into j
from sj in j.DefaultIfEmpty()
select string.Format("Outer: {0} Left: {1}", s1, sj)

输出是:

Outer: a Left: a  
Outer: b Left: b
Outer: c Left:
Outer: d Left:
Outer: e Left:

这是一个简单的左连接。现在我想添加一个新的数据集:

string[] rightouter = new string[] { "c", "d", "e" };  

期望的输出是:

Outer: a Left: a Right:  
Outer: b Left: b Right:
Outer: c Left: Right: c
Outer: d Left: Right: d
Outer: e Left: Right: e

如何重新格式化 LINQ 以解决此输出问题?谢谢

最佳答案

试试这个:

string[] all = {"a", "b", "c", "d", "e"};
string[] left = {"a", "b"};
string[] right = {"c", "d", "e"};

var q = from innerItem in all
join leftItem in left on innerItem equals leftItem into leftItems
join rightItem in right on innerItem equals rightItem into rightItems
from a in leftItems.DefaultIfEmpty()
from b in rightItems.DefaultIfEmpty()
select string.Format("Outer: {0} Left: {1} Right: {2}", innerItem, a, b);

关于c# - LINQ 右连接和左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671822/

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