0

I have a custom object that has the following properties in it's class...

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; }
    }
}

I have a list of these objects that look like the following...

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";

I want them to be sorted in order (similar to how they would be displayed in a treeview listing directory paths), for example...

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)

What the best way to achieve this? Could I do something like List<MyFile> sortedList = folders.OrderBy(p => p.Path).ToList(); ?

0

1 Answer 1

1

Yes you are correct, you can easily use linq to sort this collection of objects.

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);
}

Output:

test1  (Root)
test30  (Root)
test44  (Root)
test1  (Root/test30)
test5  (Root/test30)
SubDir  (Root/test44/SubDir)
SubDir6  (Root/test44/SubDir/SubDir6)
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I was missing! The ThenBy() was perfect. Thanks Seany84

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.