Sort list by item content and length

I am new to C # and looking for some help with the problem. I sort the list by the length of the item in the list, I will try to explain using a simplified version.

I have a list of objects for categories with the following List format:

category.Name; category.Path; 

When I extract a list of categories from an external database and import them into a list, they are not included in any 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, you can see that they do not have a special order and simply follow the order in which they were in the database. I am trying to organize 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 reinstalling 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 hierarchy based on the names of depths and categories of elements of the Path component.

If anyone can help me, it will be really great.

+4
source share
1 answer

Assuming that:

 var list = new List<Category>(); 

You have only two options:

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

or vice versa:

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

You can also order the depth of the path:

 var result = list.OrderBy(c => c.Path.Split(new[] { '\' }).Length) // less slashes -> more slashes .ThenBy(c => ...); 
+2
source

Source: https://habr.com/ru/post/1434247/


All Articles