在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中文網其他相關文章!