我的任务是将一些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以解决此输出?感谢
答案 0 :(得分:7)
试试这个:
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);