c# – 按内容和元素长度对列表进行排序

我是c#的新手,我正在寻找一些问题的帮助,我按列表中元素的长度对列表进行排序,我将尝试使用简化版本进行解释.

我有一个具有以下格式列表的类别的对象列表:

category.Name;
category.Path;

当我从外部数据库中提取类别列表并将它们导入List时,它们没有特定的顺序,例如:

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

从上面你可以看到它们没有特定的顺序,只需按照它们在数据库中的顺序.
我想要做的是使用Path元素的名称和path元素的组成部分的长度来组织它们.我需要通过重新组织列表来实现以下格式:

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

因此,List基于Path组件元素的深度和类别名称构建为层次结构.

如果有人能帮助我,那将是非常好的.

最佳答案 假设:

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 => ...);
点赞