Wednesday, October 8, 2008

C#/.NET Sort Problem

C#/.NET Sort Problem

I have a List that I want to sort. The call is:

firstArray.Sort(compare);

The comparer function is:

        public int compare (String[] p1, String[] p2)
{
int result = 0;

if (p1 == null && p2 == null)
result = 0;
else if (p1 == null)
result = -1;
else if (p2 == null)
result = 1;
else
{
if (p1[zipColumn].Equals("zip"))
result = -1;
else
{
result = (p1[zipColumn].CompareTo(p2[zipColumn]));
if (result == 0)
result = (p1[lastnameColumn].CompareTo(p2[lastnameColumn]));
}
}
return (result);
}

The exception is:

IComparer (or the IComparable methods it relies upon) did not return zero when Array.Sort called x. CompareTo(x). x: 'System.String[]' x's type: 'String[]' The IComparer: 'System.Array+FunctorComparer`1[System.String[]]'.
I'm a bit mystified by this. One possible source of confusion is that the comparer method is being called with an entry that does not appear in firstArray (one that consists of entirely nulls). Any suggestions?

UPDATE: Thanks to my helpful readers! The Sort function will, under some circumstances, pass in two pointers to the same object (which in retrospect is what the error message was saying, in an unclear way)--and when that happens, it expects to get a zero back.

I needed to verify that p1 and p2 aren't the same object.

if (Object.ReferenceEquals(p1, p2))  // p1 & p2 are  really the same object, no compare needed...      

return 0;

At the start of the compare function solves the problem!

No comments:

Post a Comment