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

前端 未结 1 1132
误落风尘
误落风尘 2021-01-14 00:03

I have the following basic classes (cut down for this question):

public class Parent
{
    public string Name { get; set; }
    public IList Chi         


        
相关标签:
1条回答
  • 2021-01-14 00:35

    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();
    
    0 讨论(0)
提交回复
热议问题