简体   繁体   中英

Nested parent child lists where order by doesn't work

I have the following code:

public class Navigation
{
    public Navigation()
    {
        SubNavigation = new List<Navigation>();
    }

    public int Order { get; set; }
    public string Text { get; set; }
    public string RouteName { get; set; }
    public IList<Navigation> SubNavigation { get; set; }
}

I then have:

IList<Navigation> list = new List<Navigation>(); 

I populate the list with some data. Not all items have a sub navigation. Currently the navigation only goes one level deep.

Now I would like to sort both the navigation and the sub-navigation for each item by order. I have tried all kinds of approaches but no matter what I tried I could not get the sub-navigation to sort without re-creating the object. The below code works:

IList<Navigation> result = list.OrderBy(l => l.Order)
                               .Select(n => new Navigation
                               {
                                   Order = n.Order,
                                   Text = n.Text,
                                   RouteName = n.RouteName,
                                   SubNavigation = n.SubNavigation.OrderBy(s => s.Order).ToList()
                               }).ToList();

I am not in love with this approach and my question is if there is any cleaner/better way of doing this using LINQ and the method syntax?

You could add a new property on your object:

public IList<Navigation> OrderedSubNavigation 
{ 
    get
    {
        return SubNavigation.OrderBy(s => s.Order).ToList();
    }

}

Then when you want the ordered one you just use that.

I have tried all kinds of approaches but no matter what I tried I could not get the sub-navigation to sort without re-creating the object.

Well no, you wouldn't be able to cleanly - because getting the subnavigation to be in a particular order requires modifying the existing object, and LINQ's not built for that. LINQ's built for queries , which shouldn't mutate the data they work on.

One option would be to only sort the subnavigation when you need to - live with the fact that it's unordered within a Navigation , and then when you actually need the subnavigation items (eg for display) you can order at that point. Aside from anything else, this will make it more efficient if you end up not displaying the subnavigation items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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