Skip to content

Commit 87714a7

Browse files
committed
Make NumericSort use InvariantCulture instead of Ordinal comparison
Ordinal comparison sorts non-alphanumeric chars (like underscore etc) differently than expected (i.e compared to filesystem sorting etc). InvariantCulture comparison corrects this, without imposing cultural differences. (A possible alternative would be CurrentCulture comparison.) The earlier code, when comparing a single digit-char against non-digit-char, used char.CompareTo() where the comparison method can not be specified. To fix this, we now use the same Comparer for all non-all-digits string comparisons.
1 parent d3610d5 commit 87714a7

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/Models/NumericSort.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ public static class NumericSort
66
{
77
public static int Compare(string s1, string s2)
88
{
9+
var comparer = StringComparer.InvariantCultureIgnoreCase;
10+
911
int len1 = s1.Length;
1012
int len2 = s2.Length;
1113

@@ -20,7 +22,7 @@ public static int Compare(string s1, string s2)
2022
bool isDigit1 = char.IsDigit(c1);
2123
bool isDigit2 = char.IsDigit(c2);
2224
if (isDigit1 != isDigit2)
23-
return c1.CompareTo(c2);
25+
return comparer.Compare(c1.ToString(), c2.ToString());
2426

2527
int subLen1 = 1;
2628
while (marker1 + subLen1 < len1 && char.IsDigit(s1[marker1 + subLen1]) == isDigit1)
@@ -40,7 +42,7 @@ public static int Compare(string s1, string s2)
4042
if (isDigit1)
4143
result = (subLen1 == subLen2) ? string.CompareOrdinal(sub1, sub2) : (subLen1 - subLen2);
4244
else
43-
result = string.Compare(sub1, sub2, StringComparison.OrdinalIgnoreCase);
45+
result = comparer.Compare(sub1, sub2);
4446

4547
if (result != 0)
4648
return result;

0 commit comments

Comments
 (0)