在自定义对象列表中对文件路径进行排序

时间:2016-04-25 18:33:02

标签: c# list c#-4.0 filepath

我有一个自定义对象,其中包含以下属性......

public class MyFile
{
    private string m_Name;
    public string Name
    {
        get { return m_Name; }
        set { m_Name= value; }
    }

    private string m_Path;
    public string Path
    {
        get { return m_Path; }
        set { m_Path= value; }
    }
}

我有一个这些对象的列表,如下所示......

listItems[0].Name = "test1"; listItems[0].Path = "Root/SubDir1/SubDir2";
listItems[1].Name = "test30"; listItems[1].Path = "Root";
listItems[2].Name = "t14"; listItems[2].Path = "Root/SubDir20/SubDir16";

我希望它们按顺序排序(类似于它们在树视图列表目录路径中的显示方式),例如......

test30   (Root)
test1    (Root/test30)
test5    (Root/test30)
test44   (Root)
SubDir   (Root/test44)
SubDir6  (Root/test44/SubDir)
test1    (Root/test44/SubDir/SubDir6)
zSubDir1 (Root)
SubDir2  (Root/zSubDir1)
test8    (Root/zSubDir1/SubDir2)
test9    (Root/zSubDir1/SubDir2)
test10   (Root/zSubDir1/SubDir2)

实现这一目标的最佳方法是什么?我可以做List<MyFile> sortedList = folders.OrderBy(p => p.Path).ToList();之类的事情吗?

1 个答案:

答案 0 :(得分:1)

是的,你是对的,你可以轻松地使用linq对这个对象集合进行排序。

var x1 = new MyFile{ Name = "test30", Path = "Root" };
var x2 = new MyFile{ Name = "test1", Path = "Root/test30" };
var x3 = new MyFile{ Name = "test5", Path = "Root/test30" };
var x4 = new MyFile{ Name = "test44", Path = "Root" };
var x5 = new MyFile{ Name = "SubDir", Path = "Root/test44/SubDir" };
var x6 = new MyFile{ Name = "SubDir6", Path = "Root/test44/SubDir/SubDir6" };
var x7 = new MyFile{ Name = "test1", Path = "Root" };
var x8 = new MyFile{ Name = "SubDir2", Path = "Root/zSubDir1" };

var lst = new List<MyFile>{
    x1,x2,x3,x4,x5,x6,x7,
};
var listItems = lst.OrderBy(x => x.Path).ThenBy(x => x.Name);

foreach(var item in listItems)
{
    Console.WriteLine("{0}  ({1})", item.Name, item.Path);
}

输出:

test1  (Root)
test30  (Root)
test44  (Root)
test1  (Root/test30)
test5  (Root/test30)
SubDir  (Root/test44/SubDir)
SubDir6  (Root/test44/SubDir/SubDir6)