CSharp (C #) - Sorting Files Returned by DirectoryInfo.GetFiles Using Natural Sort

Views: 381
Reading Time: 4 minutes

Hello people,
Good Morning!

In this post I will take a very simple approach to something that many .NET developers are looking for on the internet, as I sought this solution myself, but which is a little tricky to find because most of the posted solutions do not work.

My problem was that I use a C # function a lot in my CLR to list files from a directory (I had already posted this function in the post SQL Server - How to list, read, write, copy, delete and move files with CLR (C #)), but the fact that the files are not sorted correctly always bothered me, and I decided to improve it.

Example of current usage:
CSharp sort sorting DirectoryInfo.GetFiles by name natural sort 1

Even if you use an ORDER BY clause to try to sort, it won't work, because SQL Server will do string sorting using alphanumeric sorting.

How the alphanumeric string sorting algorithm works
This type of algorithm uses ASCII code to sort data by comparing character by character until the string ends or the ASCII code of one string is shorter than the other. Thus, in a comparison between 100 File and 20 File, the comparison will be made as follows:

  • Each character of the word "File" will be compared between the 2 strings. Since they are the same, the algorithm will proceed to the rest of the string.
  • The character “1” will be compared with the character “2”. As it is smaller, the sorting ends there by placing “100 File” before “20 File”

How the Natural Sort String Sorting Algorithm Works
Just as I worry about this ordering, which is the standard for most programming languages, so many people don't like “100” coming before “2000” and to give it a more “humanized” view, it's gone The Natural Sort algorithm, which separates numeric characters from letters, and sorts them separately. The numbers are compared numerically (where 100 is greater than 20), and the strings it continues using ASCII code.

To implement the Natural Sort algorithm, I found code in the James McCormack blog to create an ICompare class in C # and thus sort my files in my function (and any other list of files you need to sort).

View Source Code for ICompare Class

Now I need to change my file listing function (I also include a boolean flag to list files within subdirectories or not) and include an OrderBy function through the LINQ library.

In this excerpt:

I changed to this snippet:

And with that, our problem was solved, where we have the following result:
CSharp sort sorting DirectoryInfo.GetFiles by name natural sort solved

View Full Source Code for this Function

Thank you so much for visiting and see you next post!