c# - 有多个孩子的 Linq 父母
问题描述
这些是我的桌子
家长
- 父母名字
- 家长电子邮件
- ChildId1
- ChildId2
- 学校编号
孩子
- ChildId
- 子名
学校
- 学校编号
- 学校名称
我想像这样提取父母数据
ParentName, ParentEmail, SchoolName, ChildName1, ChildName2
如何在 C# 中使用 Linq 实现这一点?
我试过这个
var result = from parent
join child
join school
但它没有编译。
解决方案
这是一个 linq 查询,可以满足您的要求。我同意与您的数据结构相关的@flydog57。除非您需要强制执行 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" }
};
}
推荐阅读
- html - 访问 EJS 中的先前范围
- python - Python 使用 Bearer Token 获取 API 响应
- python - fastapi 依赖 vs 中间件
- java - 如何在单个 ec2 实例上运行多个 java 项目
- png - ImageMagick 在创建动画 gif 时是否有帧限制?
- c# - 如何使用 SelectToken 在 c# 中将字符串转换为枚举
- python - Web 抓取到 CSV 的问题 [AttributeError: 'str' object has no attribute 'text]
- c# - 从列表中选择随机词作为老虎机代码
- r - 在单个 R 代码中从设备获取多个 api 调用
- java - 获取 javax.net.ssl.SSLHandshakeException:PKIX 路径构建失败:-尽管消费服务具有 CA 证书