Linq中的lambda /方法语法中的左外连接

时间:2012-08-22 14:56:02

标签: c# .net linq

  

可能重复:
  How do you perform a left outer join using linq extension methods

我找不到Linq lambda的左外连接示例(使用扩展方法),至少不是一个明确的。

假设我有下表:

Parent
{
    PID     // PK
}

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

我想加入Parent with Child,对于每个失踪的孩子,我希望Text的默认值为“[[Empty]]”。我怎么能用linq lambda语法做到这一点?

我目前有以下内容:

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?
        });

2 个答案:

答案 0 :(得分:71)

你很亲密。以下内容将为每个孩子选择PIDCIDText,并为没有孩子的每位家长选择PIDCID = -1Text = "[[Empty]]"

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);

答案 1 :(得分:7)

from p in Parent
join c in Child on p.PID equals c.PID into g
from c in g.DefaultIfEmpty
select new 
{
   p.PID,
   CID = c != null ? (int?)c.CID : null, // Could be null
   Text = c != null ? c.Text : "[[Empty]]"
}

使用lambda:

class ChildResult
{
   public int PID { get; set; }
   public int? CID { get; set; }
   public string Text { get; set; }
}

lParent.SelectMany(p => p.Childs.Any() ?
  p.Childs.Select(c => new ChildResult() { PID = c.PID, CID = c.CID, Text = c.Text }) :
  new [] { new ChildResult() { PID = p.PID, CID = null, Text = "[[Empty]]" } } );