【问题标题】:left outer join in lambda/method syntax in Linq [duplicate]Linq中的lambda /方法语法中的左外连接[重复]
【发布时间】:2012-08-18 00:58:43
【问题描述】:

可能重复:
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?
        });

【问题讨论】:

  • 你已经尝试过什么? “linq lambda”是什么意思?
  • 我无法理解你在做什么!
  • @mellamokm 哦,非常有帮助,所有这些示例都是 lambda 语法!哦,等等,不,他们不是。 -_-
  • @SergRogovtsev 我的意思是如何使用扩展方法来做到这一点。 :P

标签: c# .net linq


【解决方案1】:

你已经接近了。以下将为每个孩子选择 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);

【讨论】:

    【解决方案2】:
    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]]" } } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2014-07-29
      • 1970-01-01
      • 2013-05-26
      相关资源
      最近更新 更多