Linq父母有多个孩子

时间:2020-11-01 16:45:06

标签: c# linq

这些是我的桌子

父母

  • ParentName
  • ParentEmail
  • ChildId1
  • ChildId2
  • SchoolId

孩子

  • ChildId
  • ChildName

学校

  • SchoolId
  • 学校名称

我想这样提取父母数据

ParentName, ParentEmail, SchoolName, ChildName1, ChildName2

如何在C#中使用Linq实现此目的?

我已经尝试过了

var result = from parent
             join child
             join school

但未编译。

1 个答案:

答案 0 :(得分:0)

这是一个linq查询,它将执行您所要的操作。我同意与您的数据结构有关的@ flydog57。除非您需要强制执行2子规则,否则在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" }
        };
}
相关问题