How do you sort the parent and child collections using Linq?

I have the following base classes (cut out for this question):

public class Parent { public string Name { get; set; } public IList<Child> Children { get; set; } } public class Child { public string Name { get; set; } } 

If I have a parent collection, then I would like to get an IList that is sorted by Parent.Name, as well as children for each parent should be sorted by their name.

I tried this (which only sorts parents, not children):

 IList<Parent> parents = ... //Populated parents.OrderBy(p => p.Name).ThenBy(p => p.Children.OrderBy(c => c.Name)).ToList() 

I searched but can't find anything (maybe I'm dumb).

Any suggestions for Linq newbies?

Thank you in advance

Andy

+4
source share
1 answer

First of all, calling OrderBy on the list, as you do, will not sort it in place. It will return a new sorted IEnumerable ; you can use .ToList() to turn it into a list, but it will still be a copy. Now about sorting. You really need to not only arrange the items in the collection, but also make a copy of each item that would sort its Children . So:

 IList<Parent> parents = ... //Populated parents = (from p in parents orderby p.Name select new Parent { Name = p.Name, Children = p.Children.OrderBy(c => c.Name).ToList() } ).ToList(); 
+4
source

All Articles