2
var files = Directory.GetFiles(@"C:\Users\user\Downloads\CaptchaCollection\Small").OrderBy(name => name).ToArray();

for (int i = 0; i < files.Length; i++)
{
    MessageBox.Show(files[i].ToString());
}

So I was testing my files array with the message box but it seems like it's not giving the name in order.

My file names are n.png, where n is a number. There is no pattern since I deleted some images.

So here is the output so far:

1
1001
1006
1008
1009
101
1016
1017
1019
1026
....

Normally in ascending order manually I'd get something like:

1
2
4
5
7
...

How do I sort this array so that everything is in numeric order??

i3arnon
  • 113,022
  • 33
  • 324
  • 344
puretppc
  • 3,232
  • 8
  • 38
  • 65

1 Answers1

4

The list is ordered in alphabetical order. What you want is to order them as numbers. You can do that if they are numbers:

Directory.GetFiles(@"C:\Users\user\Downloads\CaptchaCollection\Small").
    Select(name => int.Parse(Path.GetFileNameWithoutExtension(name))).
    OrderBy(number => number).
    ToArray();

If you would want to filter out filenames that would not be a number while still using linq you could do this:

Directory.GetFiles(@"C:\Users\user\Downloads\CaptchaCollection\Small").
    Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension)).
    Where(name => {int number; return int.TryParse(name, out number);}).
    Select(name => int.Parse(name)).
    OrderBy(number => number).
    ToArray();
i3arnon
  • 113,022
  • 33
  • 324
  • 344
  • 1
    Thanks so much :) @Steve Thanks for pointing this out too in case I accidentally put some non-numerics there. – puretppc Jan 25 '14 at 01:42