Bug .NET System.Collections Sort with example in C#

  • Thread starter Thread starter william.hooper
  • Start date Start date
W

william.hooper

There is a longer article about this subject here:
http://www.codeproject.com/useritems/SortedList_Bug.asp
See the main article and the reply thread started by Robert Rohde.

Alternatively look at this code:

ArrayList a=new ArrayList();

string s1 = "-0.67:-0.33:0.33";
string s2 = "0.67:-0.33:0.33";
string s3 = "-0.67:0.33:-0.33";

a.Add(s1);
a.Add(s2);
a.Add(s3);

a.Sort();
for (int i=0; i<3; i++) Console.WriteLine( a );

Console.WriteLine();

a.Clear();
a.Add(s1);
a.Add(s3);
a.Add(s2);

a.Sort();
for (int i=0; i<3; i++) Console.WriteLine( a );

This code produces the following six lines of output:

-0.67:0.33:-0.33
0.67:-0.33:0.33
-0.67:-0.33:0.33

-0.67:-0.33:0.33
-0.67:0.33:-0.33
0.67:-0.33:0.33

Note that the .Sort produces different outputs depending on the order
the strings are added.

It looks like the Sort algorithm is ignoring the "-" mark.

This is a very serious Bug impacting the System.Collections Array,
SortedList etc.
 
Sorry I posted this on another news group and
microsoft.public.dotnet.languages.csharp and it has had good response
there.

The problem is the comparer:

string s1 = "-0.67:-0.33:0.33";
string s2 = "0.67:-0.33:0.33";
string s3 = "-0.67:0.33:-0.33";

Console.WriteLine( String.Compare(s1,s2));
Console.WriteLine( String.Compare(s2,s3));
Console.WriteLine( String.Compare(s3,s1));
Console.WriteLine();
Console.WriteLine( String.CompareOrdinal(s1, s2));
Console.WriteLine( String.CompareOrdinal(s2, s3));
Console.WriteLine( String.CompareOrdinal(s3, s1));

returns:

1
1
1

-3
3
3

So the String.Compare is giving crazy results with this example.

It is not ignoring the hyphens - which would return 0,0,0 but instead
1,1,1. The String.Compare function works OK if you have one hypen in a
string, but it can get confused if there are two hyphens in the text.

Using String.CompareOrdinal fixes the problem but the String.Compare
looks buggy, and if not this example should at least be posted in the
documentation.
 
Back
Top