0

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,
            },
    },
}
Muhammad Sulaiman
  • 2,399
  • 4
  • 14
  • 28
  • Your code is close - but if `GrandChildren` contains multiple `GrandChild`s, which do you want to use to sort the parent? – NetMage Oct 06 '22 at 19:00
  • tried this one but it would'nt let me var addressSort = addresses.OrderByDescending(j => j.Contracts.Jobs.HireDate).ToArray(); it says doesnt contain a definition for jobs. Address is the Parent, Contracts is the Child, and Jobs is the GrandChild – Franco Neil Glovasa Oct 06 '22 at 23:25
  • C# is a language of types. What is the type of `Jobs`? Does that type have a property or field named `HireDate`? Or is `Jobs` a collection, and `HireDate` a property of a single `Job` and then we get back to my original question - which `Job.HireDate` do you want to sort by? – NetMage Oct 07 '22 at 18:18

0 Answers0