Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
c# .net tilde (ascii 126) when sorting a string seems to come before 1 (ascii 49) is this correct?
"I", "~J", "123", "K", "~E", "A", "~G", "U"
I expected the order to be 123, A, I, J, K, U, ~E, ~G, ~J
Not ~E, ~G, ~J, 123, A, I, K, U
Posted

1 solution

C# is .NET, so it defaults to Unicode characters, not ASCII - however, this makes little different in unaccented English.

The unicode character order is exactly as you would expect: http://unicode-table.com/en/[^] and a quick check:
C#
string[] data = {"I", "~J", "123", "K", "~E", "A", "~G", "U"};
Array.Sort(data);
foreach (string s in data)
    {
    Console.WriteLine(s);
    }
shows exactly what you see!

But that's because it's using the default comparer, which is not an ordinal compare - it's a linguistic comparison!
Try using an Ordinal comparison:
C#
string[] data = {"I", "~J", "123", "K", "~E", "A", "~G", "U"};
Array.Sort(data, StringComparer.Ordinal);
foreach (string s in data)
    {
    Console.WriteLine(s);
    }

And you will get the result you want:
123
A
I
K
U
~E
~G
~J
 
Share this answer
 
v2
Comments
TheRealSteveJudge 16-Mar-15 8:53am    
5*
Eamon Carron 16-Mar-15 9:54am    
Many thanks and nicely explained.
OriginalGriff 16-Mar-15 10:04am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900