30

可能重复:
如何使用 linq 扩展方法执行左外连接

我找不到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?
        });
4

2 回答 2

78

你很近。以下将为每个孩子选择PID,CID和,对于没有孩子的每个父母选择 ,和:TextPIDCID = -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);
于 2012-08-22T15:44:43.853 回答
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]]" } } );
于 2012-08-22T15:03:51.690 回答