andypike
andypike

Reputation: 551

How do you sort a parent and child collection using Linq?

I have the following basic classes (cut down 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, what I'd like to do is get an IList that is sorted by Parent.Name and also the Children for each parent need to be sorted by their Name.

I've tried this (which only sorts the Parents, not the Children):

IList<Parent> parents = ... //Populated

parents.OrderBy(p => p.Name).ThenBy(p => p.Children.OrderBy(c => c.Name)).ToList()

I've searched but can't find anything (probably me being dumb).

Any suggestions for a Linq newbie?

Thanks in advance

Andy

Upvotes: 4

Views: 6166

Answers (2)

Diogo
Diogo

Reputation: 616

Same solution, using LINQ method syntax:

IList<MyType> myTypeList = ... //Populated

var sortedList = myTypeList.Select(t =>
{
    t.Children = t.Children.OrderBy(c => c.Name).ToList();
    return t;
}).ToList();

Upvotes: 0

Pavel Minaev
Pavel Minaev

Reputation: 101555

First of all, calling OrderBy on the list, the way you do, won't sort it in-place. It will return a new sorted IEnumerable; you can use .ToList() on that to turn it into a list, but it will still be a copy. Now on to the sorting itself. You really need to not just order the items in the collection, but make a copy of each item which would have its Children sorted as well. 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();

Upvotes: 4

Related Questions