Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.Sort ArgumentException error: IComparer doesn't not return 0(null)

Tags:

c#

c#-3.0

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

like image 237
S. Richter Avatar asked Dec 28 '22 23:12

S. Richter


1 Answers

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;
        }
    });
like image 106
Paolo Tedesco Avatar answered Jan 27 '23 15:01

Paolo Tedesco