在LINQ中无需join-on-equals-into
子句执行左外部联接
在C# LINQ to objects中,可以使用DefaultIfEmpty()
方法执行不使用join-on-equals-into
子句的左外部联接。
左外部联接的解决方案
要使用Where
子句执行左外部联接,请修改代码如下:
<code class="language-csharp">List<joinpair> leftFinal = (from l in lefts join r in rights on l.Key equals r.Key into temp from r in temp.DefaultIfEmpty() select new JoinPair { LeftId = l.Id, RightId = r == null ? 0 : r.Id });</code>
说明
DefaultIfEmpty()
方法如果联接条件不匹配,则返回正在联接的集合类型的默认值(在本例中为JoinPair
)。这确保了左表(lefts
)中的所有行都包含在结果中,即使右表(rights
)中没有匹配的行。
示例
考虑为内部联接提供的代码:
<code class="language-csharp">List<joinpair> innerFinal = (from l in lefts from r in rights where l.Key == r.Key select new JoinPair { LeftId = l.Id, RightId = r.Id });</code>
要实现左外部联接,请将Where
子句替换为以下内容:
<code class="language-csharp">join r in rights on l.Key equals r.Key into temp from r in temp.DefaultIfEmpty()</code>
此修改将确保左表lefts
中的所有行都包含在结果中,包括在右表rights
中没有匹配行的那些行。
以上是如何在没有```of-on-equals-into)子句中执行LINQ中的外部连接?的详细内容。更多信息请关注PHP中文网其他相关文章!