n1warhead n1warhead - 1 month ago 5x
C# Question

C# Sort a list from the values of another list

hoping you can help me with this.

Okay I have two lists.

List1 - Gets the names of files without a path (so I can list the names on dynamically created buttons). More so for visual purposes only.

List2 - Stores the actual path to the file.

Now I have done List1.Sort(); and List2.Sort().
But being they are alphabetical, A direct path from C:/// is different than Hello.png. <(Just an example name)>

So the problem I am facing is, List1 and 2 aren't identical in where the actual elements are stored. (Which does make sense).

So is there a way to like sort List2 to match the same order as List1? Or vice versa.. So when I click the button, it loads the proper image,etc that it needs to.


I agree with the comments above, use a single list of full paths and use the System.Io.Path.FileName method to order by file name regardless of directory.

        var list2 = new List<string>() { @"C:\Directory1\B.txt", @"C:\Directory2\A.txt" };
        var orderedList = list2.OrderBy(System.IO.Path.GetFileName);
        //orderedList[0] is @"C:\Directory2\A.txt"
        //orderedList[1] is @"C:\Directory1\B.txt"