簡體   English   中英

有多個孩子的 Linq 父母

[英]Linq parent with multiple children

這些是我的桌子

家長

  • 父母名字
  • 家長郵箱
  • 兒童 ID1
  • 兒童 ID2
  • 學校編號

孩子

  • 兒童ID
  • 孩子姓名

學校

  • 學校編號
  • 學校名稱

我想像這樣拉父母數據

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" }
        };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM