如何实现左连接在JOIN扩展方法 [英] How to implement left join in JOIN Extension method

查看:138
本文介绍了如何实现左连接在JOIN扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个外连接上这种类型的查询对 p.Person 表。
我将如何做到这一点。



这例子是从 HTTP采取? //ashishware.com/DSLinqExample.shtml

  VAR onlyinfo = p.Person 
。凡( N => n.FirstName.Contains('A'))
。加入(p.PersonInfo,$ b $亿=> n.PersonId,
M = GT; m.PersonId,
(N,M)=>米)
.ToArray&所述; Persons.PersonInfoRow>();


解决方案

通常左联接在LINQ与组联接蓝本,有时与 DefaultIfEmpty 的SelectMany 结合:

  VAR leftJoin = p.Person.Where(N => n.FirstName.Contains(A))
.GroupJoin(p.PersonInfo,$ b $亿=> n.PersonId,
M = GT; m.PersonId,
(N,MS)=>新建{N,MS = ms.DefaultIfEmpty()})
.SelectMany(Z => ; z.ms.Select(M = gt;新建{N =锌,M));

这将使对(N,M),其中 n的序列 p.Person 和 M p.PersonInfo ,但 M 如果没有匹配的将是空的。



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


I am trying to implement an outer join on this kind of query for the p.Person table. How would I do this?

This example is taken from http://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<Persons.PersonInfoRow>();

解决方案

Normally left joins in LINQ are modelled with group joins, sometimes in conjunction with DefaultIfEmpty and SelectMany:

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 = z.n, m ));

That will give a sequence of pairs (n, m) where n is the entry from p.Person and m is the entry from p.PersonInfo, but m will be null if there are no matches.

(It's completely untested, btw - but should give you the idea anyway :)

这篇关于如何实现左连接在JOIN扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆