30

重複の可能性:
linq拡張メソッドを使用して左外部結合をどのように実行しますか

Linqラムダ(拡張メソッドを使用)の左外部結合の例を見つけることができません。少なくとも、明確な例ではありません。

次の表があるとしましょう。

Parent
{
    PID     // PK
}

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

親と子を結合したいのですが、欠落しているすべての子について、Textのデフォルト値を「[[Empty]]」にします。linqラムダ構文でこれを行うにはどうすればよいですか?

私は現在次のものを持っています:

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各子Text、およびPIDCID = -1および子Text = "[[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]]"
}

ラムダの場合:

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 に答える