Linq parent with multiple children

Here is a linq query that will do what you’re asking for. I do agree with @flydog57 related to your data structure. 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.

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 = "[email protected]", Child1Id = 1, Child2Id = 2, SchoolId = 1 },
            new Parent { ParentName = "Lulubelle", ParentEmail = "[email protected]", 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" }
        };
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top