根据字符数排序列表<string>

时间:2017-06-26 10:53:37

标签: c# string list sorting

示例:

List<string> folders = new List<string>();
folders.Add("folder1/folder2/folder3/");
folders.Add("folder1/");
folders.Add("folder1/folder2/");

我想根据字符排序此列表,即&#39; /&#39; 所以我的输出将是
folder1 /
folder1 / folder2 /
folder1 / folder2 / folder3

2 个答案:

答案 0 :(得分:7)

LINQ:

folders = folders.OrderBy(f => f.Length).ToList(); // consider null strings

List.Sort

folders.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));

如果列表可以包含null的安全方法:

folders = folders.OrderBy(f => f?.Length ?? int.MinValue).ToList();

如果您确实想要按文件夹深度而不是字符串长度排序:

folders = folders.OrderBy(f => f.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Length).ToList();  

答案 1 :(得分:0)

您可能真的想按名称排序:

folders = folders.OrderBy(f => f).ToList();

或者简单地说:

folders.Sort();

这适用于以下情况:

folder1/
folder1/subfolder1
folder1/subfolder1/subsubfolder
folder2
folder2/subfolder2

仅按长度排序会将"folder1""folder2"视为相同。