[英]Linq parent with multiple children
These are the tables I have这些是我的桌子
Parent家长
Child孩子
School学校
I want to pull parents data like this我想像这样拉父母数据
ParentName, ParentEmail, SchoolName, ChildName1, ChildName2
How can I achieve this using Linq in C#?如何在 C# 中使用 Linq 实现这一点?
I have tried this我试过这个
var result = from parent
join child
join school
but it is not compiling.但它没有编译。
Here is a linq query that will do what you're asking for.这是一个 linq 查询,可以满足您的要求。 I do agree with @flydog57 related to your data structure.
我同意 @flydog57 与您的数据结构相关的观点。 Unless you need to enforce the 2 kid rule, it would make a lot more sense to have a SchoolId, and Parent1 Parent2 on the Child table, rather than the other way around.
除非您需要强制执行 2 child 规则,否则在 Child 表上有一个 SchoolId 和 Parent1 Parent2 会更有意义,而不是相反。
void Main()
{
var parents = GetParents();
var children = GetChildren();
var schools = GetSchools();
var child1parent = children.Join(parents, c => c.ChildId, p => p.Child1Id, (c, p) => new { Child = c, Parent = p });
var child2parent = children.Join(parents, c => c.ChildId, p => p.Child2Id, (c, p) => new { Child = c, Parent = p });
var results = child1parent
.Join(child2parent, c1 => c1.Parent.Child2Id, c2 => c2.Child.ChildId, (c1, c2) => new { Parent = c1.Parent, Child1 = c1.Child, Child2 = c2.Child })
.Join(schools, x => x.Parent.SchoolId, s => s.SchoolId, (x, s) => new { Parent = x.Parent, Child1 = x.Child1, Child2 = x.Child1, School = s })
.Select(x => new { x.Parent, x.School, x.Child1, x.Child2 });
results.ToList().ForEach(x => Console.WriteLine($"{x.Parent.ParentName} {x.Parent.ParentEmail}, {x.School.SchoolName}, {x.Child1.ChildName}, {x.Child2.ChildName}"));
}
public class Parent
{
public string ParentName { get; set; }
public string ParentEmail { get; set; }
public int Child1Id { get; set; }
public int Child2Id { get; set; }
public int SchoolId { get; set; }
}
public class Child
{
public int ChildId { get; set; }
public string ChildName { get; set; }
}
public class School
{
public int SchoolId { get; set; }
public string SchoolName { get; set; }
}
public List<Parent> GetParents()
{
return
new List<Parent>
{
new Parent { ParentName = "Donald", ParentEmail = "donald@disney.com", Child1Id = 1, Child2Id = 2, SchoolId = 1 },
new Parent { ParentName = "Lulubelle", ParentEmail = "Lulubelle@disney.com", Child1Id = 3, Child2Id = 4, SchoolId = 1 },
};
}
public List<Child> GetChildren()
{
return
new List<Child>
{
new Child { ChildId = 1, ChildName = "Huey" },
new Child { ChildId = 2, ChildName = "Dewey" },
new Child { ChildId = 3, ChildName = "Fethry" },
new Child { ChildId = 4, ChildName = "Abner" }
};
}
public List<School> GetSchools()
{
return
new List<School>
{
new School { SchoolId = 1, SchoolName = "Disney School of Rock" }
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.