How to sort object array grandchild on linq

61 Views Asked by At

I'm having a problem on sorting objects through grandchild property. I wish to sort the array of Parent through Grandchild birthdate properties. Is there any Linq to this? something like parents = parents.Orderby(gc => gc.Child.GrandChild.Birthdate).ToArray.

I know there's no such thing but you get the idea.

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public ICollection<GrandChild> GrandChildren { get; set; }
}

public class GrandChild
{
    public int Id { get; set; }
    public DateTime Birthdate { get; set; }
}

I want to sort the Parent through GrandChild's Birthdate. Any idea how?

{ 
    Name: Parent1,
    Children {
        Name: Child1,
        GrandChild {
            Name: GChild1,
            Birthdate: 1/1/80,
                },
        GrandChild {
            Name: GChild2,
            Birthdate: 1/2/80,
            },
          },
    Children {
        Name: Child2,
        GrandChild {
            Name: GChild3,
            Birthdate: 1/1/81,
                },
        GrandChild {
            Name: GChild4,
            Birthdate: 1/2/81,
            },
    },
    Name: Parent2,
    Children {
        Name: Child3,
        GrandChild {
            Name: GChild5,
            Birthdate: 1/1/82,
                },
        GrandChild {
            Name: GChild6,
            Birthdate: 1/2/82,
            },
          },
    Children {
        Name: Child4,
        GrandChild {
            Name: GChild7,
            Birthdate: 1/1/83,
                },
        GrandChild {
            Name: GChild8,
            Birthdate: 1/2/83,
            },
    },
}
0

There are 0 best solutions below