.NET 10 Numeric String Sorting: Put File 10 After File 9
When I display generated filenames, .NET 10 numeric string sorting gives me the order people usually expect: file9.txt before file10.txt . The new CompareOptions.NumericOrdering flag handles digit runs without a handwritten natural-sort parser. That sounds like a presentation-only change. It is not. The same comparer also decides whether two strings are equal, which can quietly collapse file2.txt…
When displaying filenames, .NET 10's new NumericOrdering flag sorts digit runs by numeric value rather than their ordinal position. This provides an expected ordering of file numbers, such as file9.txt before file10.txt. The same comparer is also used for equality checks, which can collapse seemingly distinct file names like file2.txt and file02.txt into a single entry in sets or dictionaries.
To achieve the desired sorting behavior, a custom StringComparer can be created with the NumericOrdering flag using CultureInfo.InvariantCulture. This comparer can then be used with the Order method to sort a list of filenames. The output shows the files sorted correctly: file2.txt, file02.txt, file9.txt, and file10.txt.
The numeric sorting also affects equality checks. Leading zeros do not alter the numeric value of a digit run, so file2.txt and file02.txt are considered equal when using the numeric comparer. This behavior can be useful for deduplication purposes but may be undesirable when file names must remain distinct.
While numeric sorting improves the visual ordering of filenames, it should not be used for parsing signed numbers, decimals, dates, semantic versions, or other complex numeric representations. It is also unsuitable for security-sensitive equality checks like IndexOf, StartsWith, or EndsWith. For these cases, ordinal comparison is recommended.
In summary, .NET 10's NumericOrdering feature provides a convenient way to sort filenames by their numeric values, but its usage should be carefully considered based on the specific requirements of the application.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.