如何使用LINQ你整理一个父母和孩子收集? [英] How do you sort a parent and child collection using Linq?

查看:109
本文介绍了如何使用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; }
}

如果我有一个父集合,我想要做的就是由Parent.Name排序,还需要孩子每个父母以他们的商品名称排序一个IList。

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).

有关LINQ的新手有什么建议?

Any suggestions for a Linq newbie?

在此先感谢

刘德华

推荐答案

首先,调用排序依据列表中,你的方式上,也不会排序到位。它会返回一个新的排序的IEnumerable ;您可以使用 .ToList()上把它变成一个列表,但它仍然是一个副本。现在就来排序本身。你真的需要不只是为了集合中的项目,但要每个项目这将对副本的孩子排序。所以:

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();

这篇关于如何使用LINQ你整理一个父母和孩子收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆