简体   繁体   中英

Different sorting results on different CLR versions

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM