LINQ Max Grandchild

时间:2012-03-12 14:08:27

标签: c# entity-framework linq-to-sql linq-to-entities

我在Entity Framework Code First中有以下对象层次结构:

class Parent {
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}

class Child { 
    public int Id { get; set; }
    public int ParentId { get; set; }

    public virtual ICollection<Grandchild> Grandchildren { get; set; }
}

class Grandchild {
    public string Name { get; set; }
    public int Age { get; set; }
}

我想找回父母的名单和他们最大的孙子的年龄。如果我的数据库中有2个父母,则每个父母有2个孩子,每个孩子有2个孩子:

Parent 1
    Child 1
        Grandchild 1 - Age 10
        Grandchild 2 - Age 15
    Child 2
        Grandchild 3 - Age 3
        Grandchild 4 - Age 7
Parent 2
    Child 3
        Grandchild 5 - Age 1
        Grandchild 6 - Age 9
    Child 4
        Grandchild 7 - Age 18
        Grandchild 8 - Age 16

我希望查询返回两个对象:

var expected = new List<anon>
{
    new { Name = "Parent 1", MaxAge = 15 },
    new { Name = "Parent 2", MaxAge = 18 }
};

如何在LINQ to Entities中编写?

修改
此外,是否有可能将孙子的名字和他们的年龄一起归还?基本上有孙子的最大年龄和孙子是谁?

2 个答案:

答案 0 :(得分:3)

from parent in db.Parents
select new
{
    Name = parent.Name,
    MaxAge = (
        from child in parent.Children
        from grandchild in child.Grandchildren
        select grandchild.Age)
        .Max()
};

答案 1 :(得分:1)

你可以这样做:

var query = from p in parents
            select
            {
              Name = p.Name,
              MaxAge = p.SelectMany(parent => parent.children)
                .SelectMany(child => child.children)
                .Max(i => i.Age)
            };