Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different sorting results on different CLR versions

Tags:

c#

.net

While comparing strings in C#, different clr gives different results on Windows 7 sp1 x64. Here is sample code:

List<string> myList = new List<string>();
myList.AddRange(new[] { "!-", "-!", "&-l", "&l-", "-(", "(-", "-*", "*-", ".-", "-.", "/'", "-/" });
myList.Sort();
Console.WriteLine(Environment.Version);
myList.ForEach(Console.WriteLine);
Console.WriteLine();
Console.WriteLine(string.Compare("!-", "-!"));
Console.WriteLine("!-".CompareTo("-!"));

Here is the sample output:


If I set Target Framework to 4.0:

4.0.30319.18444
!-
-!
&l-
&-l
(-
-(
*-
-*
.-
-.
/'
-/

-1
-1

If I set Target Framework to 2.0:

2.0.50727.5485
-!
!-
&-l
&l-
-(
(-
-*
*-
-.
.-
-/
/'

1
1

Am I missing anything?

like image 243
user1014639 Avatar asked Feb 25 '15 11:02

user1014639


1 Answers

Please ensure that you are sorting with the MyList.Sort(StringComparer.Ordinal).

Unless Unicode start changing the code of their characters, it should provide a constant sorting order. Ordinal will be based off the actual code ID that were assigned to them.

If I take your first example comparing this :

-!
!-

The hyphen is U+002D and the exclamation mark is U+0021. Those codes haven't changed since at least the ASCII tables. I would consider checking your sorting parameters to make sure you compare only on ordinal and not on actual neutral/specific cultures.

like image 127
Maxime Rouiller Avatar answered Sep 22 '22 01:09

Maxime Rouiller