4

I am new to c# and am looking for a bit of help with a problem I have sorting a list by the length of an element within the list, I will try to explain using a simplified version.

I have an Object List for categories with the following format List:

category.Name;
category.Path;

When I extract the list of categories from the external database and import them into the List they come in in no particular order, for example:

Luxury Seats      /Base/Seats
Small Seats       /Base/Seats/Luxury Seats
Seats             /Base
Small Gloves      /Base/Gloves
Large Seats       /Base/Seats/Luxury Seats
Small Red Gloves  /Base/Gloves/Small Gloves
Gloves            /Base
Budget Seats      /Base/Seats/Luxury Seats/Small Seats

From the above youcan see that they are in no particular order and simply follow the order they were in in the database. What I am trying to do is to organise them using both the name of the Path element and the length of the component parts of the path element. I need to achieve the following format by re-organising the list:

Seats             /Base
Luxury Seats      /Base/Seats
Small Seats       /Base/Seats/Luxury Seats
Budget Seats      /Base/Seats/Luxury Seats/Small Seats
Large Seats       /Base/Seats/Luxury Seats
Gloves            /Base
Small Gloves      /Base/Gloves
Small Red Gloves  /Base/Gloves/Small Gloves

So the List is structured into a heirarchy based on the depth and category names of the Path component elements.

If anyone can help me out that would be really great.

4

1 回答 1

2

假设:

var list = new List<Category>();

你只有两个选择:

var result = list.OrderBy(c => c.Name) // Luxury Seats; Seates (L -> S)
                 .ThenBy(c => c.Path); // /Base; /Base/Seats (shorter -> longer)

或相反亦然:

var result = list.OrderBy(c => c.Path) // /Base; /Base/Seats
                 .ThenBy(c => c.Name); // Luxury Seats; Seates

您也可以按路径深度排序:

var result = list.OrderBy(c => c.Path.Split(new[] { '\' }).Length) // less slashes -> more slashes
                 .ThenBy(c => ...);
于 2012-09-14T16:16:56.687 回答