首頁 > 後端開發 > C++ > 如何在沒有```of-on-equals-into)子句中執行LINQ中的外部連接?

如何在沒有```of-on-equals-into)子句中執行LINQ中的外部連接?

Patricia Arquette
發布: 2025-02-02 14:31:09
原創
906 人瀏覽過

How to Perform Left Outer Joins in LINQ without `join-on-equals-into` Clauses?

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板