2

I have the following hierarchy of objects in 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; }
}

I want to retrieve a list of parents and the age of their oldest grandchild. If I have 2 parents in my database, each parent has 2 children, and each child has 2 children:

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

I want the query to return two objects:

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

How can I write this in LINQ to Entities?

Edit
Also, is it possible to return the grandchilds name along with their age? Basically have the max age of the grandchild and who that grandchild is?

Dismissile
  • 32,564
  • 38
  • 174
  • 263

2 Answers2

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()
};
Steven
  • 166,672
  • 24
  • 332
  • 435
2

You can do this:

var query = from p in parents
            select
            {
              Name = p.Name,
              MaxAge = p.SelectMany(parent => parent.children)
                .SelectMany(child => child.children)
                .Max(i => i.Age)
            };
ntziolis
  • 10,091
  • 1
  • 34
  • 50