Linq 中的lambda /方法语法中的左外连接
可能重复:
如何使用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? });
你很亲密 以下内容将为每个子节点选择PID
, CID
和Text
,并为没有子节点的每个父节点选择PID
, CID
CID = -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);
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]]" } } );