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

标签 c# .net list sorting

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

我有一个类别的对象列表,列表格式如下:

category.Name;
category.Path;

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

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

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

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

因此,根据 Path 组件元素的深度和类别名称,将 List 结构化为一个层次结构。

如果有人能帮助我,那就太好了。

最佳答案

假设:

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

关于c# - 按元素的内容和长度对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12428245/

相关文章:

c# - 从代码启动卸载程序

python - Python 中循环直到列表不为空

c# - 使用另一个线程将数据从数据库加载到组合框

c# - 如何使用 C# 返回序列化为 JSON

c# - Entity Framework Code First Auditing 多对多和一对多问题

c# - 使用 Naudio 或 Win API 同时播放多个 .wav 文件

c# - 使用 C# 从通讯组列表中获取电子邮件地址

c# - EnterUpgradeableReadLock 和 EnterReadLock 有什么区别?

c# - 清除属性(property)-(公共(public))列表而不清除私有(private)列表

C 在链表开头插入元素