Csharp/C#教程:如何在JOIN扩展方法中实现左连接分享


如何在JOIN扩展方法中实现左连接

我试图在p.Person表的这种查询上实现外连接。 我该怎么办?

此示例来自https://ashishware.com/DSLinqExample.shtml

 var onlyinfo = p.Person .Where(n => n.FirstName.Contains('a')) .Join(p.PersonInfo, n => n.PersonId, m => m.PersonId, (n, m) => m) .ToArray(); 

通常,LINQ中的左连接使用组连接建模,有时与DefaultIfEmptySelectMany一起建模:

 var leftJoin = p.Person.Where(n => n.FirstName.Contains("a")) .GroupJoin(p.PersonInfo, n => n.PersonId, m => m.PersonId, (n, ms) => new { n, ms = ms.DefaultIfEmpty() }) .SelectMany(z => z.ms.Select(m => new { n = zn, m })); 

这将给出一系列对(n,m),其中n是来自p.Person的条目, m是来自p.PersonInfo的条目,但是如果没有匹配则m将为null。

(它完全未经测试,顺便说一句 – 但无论如何应该给你这个想法:)

对于Left outer Join尝试以下查询。 这是经过测试的

 var leftJoin = Table1 .GroupJoin( inner: Table2, outerKeySelector: t1 => t1.Col1, innerKeySelector: t2 => t2.Col2, resultSelector: ( t1, t2Rows ) => new { t1, t2Rows.DefaultIfEmpty() } ) .SelectMany( z => z.t2Rows.Select( t2 => new { t1 = z.t1, t2 = t2 } ) ); 

如果有人遇到这个问题,并想要一个扩展方法来实现这一点,我使用与其他答案相同的方法创建了一个。 它具有与常规连接扩展方法相同的签名。

上述就是C#学习教程:如何在JOIN扩展方法中实现左连接分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  public static IEnumerable LeftJoin(this IEnumerable outer, IEnumerable inner, Func outerKeySelector, Func innerKeySelector, Func resultSelector) { return outer .GroupJoin(inner, outerKeySelector, innerKeySelector, (outerObj, inners) => new { outerObj, inners= inners.DefaultIfEmpty() }) .SelectMany(a => a.inners.Select(innerObj => resultSelector(a.outerObj, innerObj))); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1012796.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐