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