左外连接中的LINQ的lambda /方法的语法 [英] left outer join in lambda/method syntax in Linq

查看:752
本文介绍了左外连接中的LINQ的lambda /方法的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/584820/how-do-you-perform-a-left-outer-join-using-linq-extension-methods">How你执行一个左外连接使用LINQ扩展方法

我找不到的LINQ的lambda(扩展方法),至少,没有一个明确的。

的左外连接的例子

比方说,我有如下表:

 父
{
    PID // PK
}

儿童
{
    CID // PK
    PID // FK
    文本
}
 

我想加入家长与儿童,并为每一个孩子不见了,我要为文本是[[空]的默认值。我怎样才能做到这一点的LINQ lambda语法?

目前,我有以下几点:

 无功源= lParent.GroupJoin(
    lChild,
    P =&GT; p.PID,
    C =&GT; c.PID,
    (P,G)=&GT;
        新// ParentChildJoined
        {
            PID = p.PID;
            //我怎么在这里添加子值?
        });
 

解决方案

您正在接近。下面将选择 PID CID 文本为每孩子, PID CID = -1 文本=[空] 为每个父无子女:

 无功源= lParent.GroupJoin(
    lChild,
    P =&GT; p.PID,
    C =&GT; c.PID,
    (P,G)=&GT; G
        。选择(C =&gt;新建{PID = p.PID,CID = c.CID,文本= c.Text})
        .DefaultIfEmpty(新{PID = p.PID,CID = -1,文本=[空]}))
    .SelectMany(G =&GT; G);
 

Possible Duplicate:
How do you perform a left outer join using linq extension methods

I can't find a left outer join example of Linq lambda (with extension methods), at least, not a clear one.

Let's say I have the following table:

Parent
{
    PID     // PK
}

Child
{
    CID     // PK
    PID     // FK
    Text
}

I want to join Parent with Child, and for every child missing, I want the default value for Text to be "[[Empty]]". How can I do this with linq lambda syntax?

I currently have the following:

var source = lParent.GroupJoin(
    lChild,
    p => p.PID,
    c => c.PID,
    (p, g) =>
        new // ParentChildJoined
        {
            PID = p.PID;
            // How do I add child values here?
        });

解决方案

You're close. The following will select PID, CID and Text for each child, and PID, CID = -1 and Text = "[[Empty]]" for each parent with no children:

var source = lParent.GroupJoin(
    lChild,
    p => p.PID,
    c => c.PID,
    (p, g) => g
        .Select(c => new { PID = p.PID, CID = c.CID, Text = c.Text })
        .DefaultIfEmpty(new { PID = p.PID, CID = -1, Text = "[[Empty]]" }))
    .SelectMany(g => g);

这篇关于左外连接中的LINQ的lambda /方法的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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