简体   繁体   English

如何使用 Linq 对父子集合进行排序?

[英]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.如果我有一个 Parent 集合,我想要做的是获得一个按 Parent.Name 排序的 IList,并且每个父项的子项也需要按其名称排序。

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?对 Linq 新手有什么建议吗?

Thanks in advance提前致谢

Andy安迪

First of all, calling OrderBy on the list, the way you do, won't sort it in-place. 首先,以这种方式调用列表中的OrderBy不会就地对其进行排序。 It will return a new sorted IEnumerable ; 它将返回一个新排序的IEnumerable ; you can use .ToList() on that to turn it into a list, but it will still be a copy. 您可以在其上使用.ToList()将其转换为列表,但它仍将是副本。 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. 您确实不仅需要订购集合中的项目,还需要复制每个项目的副本,并对其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();

Same solution, using LINQ method syntax:相同的解决方案,使用 LINQ 方法语法:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM