2

I'm trying to obtaint a sorted list of the files inside a directory. This files have differentes extensions.

foreach (String File in Directory.GetFiles(directory, "*").OrderBy(f => f))
{
 stringA[i] = File;
 i++;
}

The problem is that the result is not sorted like I expected. This is what I obtein in "stringA":

1.txt
10.txt
11.png
12.png
18.png
19.txt
2.txt
21.png
22.png
23.png
24.png
25.txt
26.txt
27.txt
28.txt
29.txt
3.png
30.txt
31.txt
32..png
33..png
34..png
35.png
4.txt
40.txt
41.png etc

What I want is : 1.txt, 2.txt, 3.png, 4.txt, 5.png, 6.txt, 7, 8, 9, 10 , 11, 19, 20, 21, 29, 30...

What can I do?

3
  • please tag the technology u are using. like java c# or any one else ?? Commented Apr 2, 2016 at 14:50
  • C#. Sorry, I forgot about the tags.. Commented Apr 2, 2016 at 14:55
  • Are the files labelled as numbers like in this example? Commented Apr 2, 2016 at 15:33

2 Answers 2

2
var files = Directory.GetFiles(directory, "*")
         .Select(file => new { FileName = file, FileNumber = long.Parse(Path.GetFileNameWithoutExtension(file))  })
         .OrderBy(data => data.FileNumber);

foreach( file in files )
{
   Console.WriteLine("{0} (Number: {1})", file.FileName, FileNumber)
}

Please note that this omits any error handling you may need.

Sign up to request clarification or add additional context in comments.

Comments

0

This is called alphanumeric sorting. For custom sorting in general, implement the IComparer interface with a custom compare method that suits your need.

For alphanumeric, Dotnetpearls has an excellent example and implementation here: http://www.dotnetperls.com/alphanumeric-sorting.

Copy the AlphanumComparatorFast class, then use it like this:

        var list = Directory.GetFiles(directory);
        Array.Sort(list, new AlphanumComparatorFast());

1 Comment

Happy to help. If you don't mind, please remember to hit the check mark to the left of the answer to accept it ;-).

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.