i have the following problem and I cannot figure out where it comes from. I would appreciate help very much.
The code:
List<Point> lst = new List<Point>();
lst.Add(new Point(0, -2));
lst.Add(new Point(-1, -2));
lst.Sort(delegate (Point x,Point y)
{
if (x.X == 0)
return -1;
else if (y.X == 0)
return 1;
else
{
double retVal1 = x.Y * 1.0 / -x.X;
double retVal2 = y.Y * 1.0 / -y.X;
int retVal = -Math.Sign(retVal1 - retVal2);
return retVal;
}
});
If executed, I recieve an ArgumentException saying that IComparer doesn't not return 0(null). However, it actually cannot return anything else but -1, 0 and 1, or?
Thank you very much for your help!
Ah, btw i'm using .NET 3.5
Actually the error message says: IComparer (or the IComparable methods it relies upon) did not return zero when Array.Sort called x. CompareTo(x). x: '' x's type: 'Point' The IComparer: 'System.Array+FunctorComparer`1[System.Drawing.Point]'.
You must return 0 if the objects are identical:
lst.Sort(delegate(Point x, Point y) {
if (x.X == y.X && x.Y == y.Y) { // you are missing this
return 0;
}
if (x.X == 0)
return -1;
else if (y.X == 0)
return 1;
else {
double retVal1 = x.Y * 1.0 / -x.X;
double retVal2 = y.Y * 1.0 / -y.X;
int retVal = -Math.Sign(retVal1 - retVal2);
return retVal;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With