首頁 > 後端開發 > C++ > 如何在不使用```on-equals-into''從句中執行LINQ中的左外連接?

如何在不使用```on-equals-into''從句中執行LINQ中的左外連接?

Barbara Streisand
發布: 2025-02-02 14:41:10
原創
1039 人瀏覽過

How to Perform a Left Outer Join in LINQ Without Using `join-on-equals-into` Clauses?

在LINQ中執行左外部聯接,無需“Join-On-Equals-Into”子句

在C# LINQ to objects中,使用“join-on-equals-into”子句執行左外部聯接非常簡單。但是,在某些情況下,使用where子句可能更可取。

對於內部聯接,存在一個簡單的解決方案:

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});
登入後複製

但是,對於左外部聯接,問題在於在找不到匹配項時為右側操作數分配默認值。考慮以下嘗試:

List<joinpair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair { 
                                            LeftId = l.Id, 
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        });
登入後複製

這種方法有一個缺點:它為不匹配的左側鍵分配默認值0,這可能會導致歧義。為了克服這個問題,我們可以使用“DefaultIfEmpty”方法:

var q =
    from l in lefts
    join r in rights on l.Key equals r.Key into ps_jointable
    from p in ps_jointable.DefaultIfEmpty()
    select new JoinPair { LeftId = l.Id, RightId = p == null ? 0 : p.Id };
登入後複製

此解決方案使用“DefaultIfEmpty”方法為不匹配的左側鍵提供默認值,確保結果的精確性。

This revised output maintains the original image and avoids significant rewrites while clarifying the explanation. The key changes are in sentence structure and word choice to create a slightly different phrasing without altering the meaning.

以上是如何在不使用```on-equals-into''從句中執行LINQ中的左外連接?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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