日期:2014-05-19  浏览次数:21281 次

如何对树形字符串数据进行排序
如何对树形字符串数据进行排序

假如说一数组tb中存放了如下的字符串,

d:\ABC
d:\ABC\Y.txt
d:\ABC\X.txt
d:\ABC\Your\b.txt
d:\ABC\Your\a.txt
d:\ABC\Your
d:\ABC\My\X.txt
d:\ABC\My\Y.txt
d:\ABC\My\b\b.txt
d:\ABC\My\b\a.txt
d:\ABC\My\a\a.txt
d:\ABC\My\a\b.txt
d:\ABC\My
d:\ABC\MY\a
d:\ABC\My\b
d:\ABC\Your\1\a.txt
d:\ABC\Your\1\b.txt
d:\ABC\Your\1

很明显是一树形结构的字符串描述,但是它不是有序排放的。

如何使用一种算法使它能像资源管理器一样的排序。

使结果序列为

d:\ABC
d:\ABC\X.txt
d:\ABC\Y.txt
d:\ABC\My
d:\ABC\My\X.txt
d:\ABC\My\Y.txt
d:\ABC\MY\a
d:\ABC\My\a\a.txt
d:\ABC\My\a\b.txt
d:\ABC\My\b
d:\ABC\My\b\a.txt
d:\ABC\My\b\b.txt
d:\ABC\Your
d:\ABC\Your\a.txt
d:\ABC\Your\b.txt
d:\ABC\Your\1
d:\ABC\Your\1\a.txt
d:\ABC\Your\1\b.txt


------解决方案--------------------
如果你使用VS2005,可以参考如下的代码:

string[] paths = new string[] {
@ "d:\ABC ",
@ "d:\ABC\Y.txt ",
@ "d:\ABC\X.txt ",
@ "d:\ABC\Your\b.txt ",
@ "d:\ABC\Your\a.txt ",
@ "d:\ABC\Your ",
@ "d:\ABC\My\X.txt ",
@ "d:\ABC\My\Y.txt ",
@ "d:\ABC\My\b\b.txt ",
@ "d:\ABC\My\b\a.txt ",
@ "d:\ABC\My\a\a.txt ",
@ "d:\ABC\My\a\b.txt ",
@ "d:\ABC\My ",
@ "d:\ABC\MY\a ",
@ "d:\ABC\My\b ",
@ "d:\ABC\Your\1\a.txt ",
@ "d:\ABC\Your\1\b.txt ",
@ "d:\ABC\Your\1 "};

List <string> list = new List <string> ();
list.AddRange(paths);
list.Sort();
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}