The windows have a built-in function StrCmpLogicalW
, which will compare strings in numbers instead of letters. It is easy to make a mapper that calls this function and uses it for comparison.
public class StrCmpLogicalComparer : Comparer<string> { [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)] private static extern int StrCmpLogicalW(string x, string y); public override int Compare(string x, string y) { return StrCmpLogicalW(x, y); } }
Here is an example program that shows the difference between default sorting and StrCmpLogicalW
sorting
class Program { static void Main() { List<string> items = new List<string>() { "Example1.txt", "Example2.txt", "Example3.txt", "Example4.txt", "Example5.txt", "Example6.txt", "Example7.txt", "Example8.txt", "Example9.txt", "Example10.txt", "Example11.txt", "Example12.txt", "Example13.txt", "Example14.txt", "Example15.txt", "Example16.txt", "Example17.txt", "Example18.txt", "Example19.txt", "Example20.txt" }; items.Sort(); foreach (var item in items) { Console.WriteLine(item); } Console.WriteLine(); items.Sort(new StrCmpLogicalComparer()); foreach (var item in items) { Console.WriteLine(item); } Console.ReadLine(); } }
which outputs
Example1.txt Example10.txt Example11.txt Example12.txt Example13.txt Example14.txt Example15.txt Example16.txt Example17.txt Example18.txt Example19.txt Example2.txt Example20.txt Example3.txt Example4.txt Example5.txt Example6.txt Example7.txt Example8.txt Example9.txt Example1.txt Example2.txt Example3.txt Example4.txt Example5.txt Example6.txt Example7.txt Example8.txt Example9.txt Example10.txt Example11.txt Example12.txt Example13.txt Example14.txt Example15.txt Example16.txt Example17.txt Example18.txt Example19.txt Example20.txt
source share