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??

1

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much :) @Steve Thanks for pointing this out too in case I accidentally put some non-numerics there.

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.