首页 > 解决方案 > 有多个孩子的 Linq 父母

问题描述

这些是我的桌子

家长

孩子

学校

我想像这样提取父母数据

ParentName, ParentEmail, SchoolName, ChildName1, ChildName2

如何在 C# 中使用 Linq 实现这一点?

我试过这个

var result = from parent
             join child
             join school

但它没有编译。

标签: c#linq

解决方案


这是一个 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" }
        };
}

推荐阅读