Natural String Sorting


Natural String Sorting

Here’s the quick run down of the problem. Let’s suppose you have a list of string that contain numeric values. When you sort that list in .Net they probably don’t get returned in the manner you’d expect. They get returned based upon their ASCII string values giving you a list that looks something like the image below. This problem has already been covered quite extensively so I’m going to quickly run through the solution I ended up using.

In order to sort this list into a format we expect we need a natural (logical, humanized or whatever you prefer to call it) type of sorting. After doing the quick “research” that brought you the above links, I noticed that explorer displayed my list of directories I have been trying to sort in the manner I desired.

This led me to find a post on stackoverflow.com describing how to use a native Windows method - StrCmpLogicalW(string psz1, string psz2) - to do the type of comparison I desired. Native methods can be imported and easily wrapped up in some nice usable .NET! I have provided a link to this code for ease of use.

https://github.com/stesta/NaturalStringComparer

and the codez to use it…


Comments



Social

Author

Steve Testa
I am a developer, consultant, entrepreneur and self described foosball champion. I like to blog occassionally about technology, code, trends and the community.