在LINQ中执行左外部联接,无需“Join-On-Equals-Into”子句
在C# LINQ to objects中,使用“join-on-equals-into”子句执行左外部联接非常简单。但是,在某些情况下,使用where子句可能更可取。
对于内部联接,存在一个简单的解决方案:
<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>
但是,对于左外部联接,问题在于在找不到匹配项时为右侧操作数分配默认值。考虑以下尝试:
<code class="language-csharp">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 });</code>
这种方法有一个缺点:它为不匹配的左侧键分配默认值0,这可能会导致歧义。为了克服这个问题,我们可以使用“DefaultIfEmpty”方法:
<code class="language-csharp">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 };</code>
此解决方案使用“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中文网其他相关文章!