LINQ 右联接和左联接
本文关键字:LINQ | 更新日期: 2023-09-27 18:35:22
我的任务是重构一些对 LINQ 的 t-sql 查询。简单连接和左外部连接是明确的。这是我的代码:
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);