views:

270

answers:

3

I am trying to sort a List of 2D Points first by x co-ordinate and then by y co-ordinate. I implemented the IComparer interface as follows:

class PointComparer : IComparer<Point>
{
    public int Compare(Point x, Point y)
    {
        if (x.Y != y.Y)
        {
            return x.Y - y.Y;
        }
        else
        {
            return x.X - y.X;
        }

    }
}

And then call my sorting as follows:

pointsList.Sort(new PointComparer());

For some reason the list doesn't sort. Surely is something very simple and silly, but stuck on this for quite a while....TIA

+1  A: 

Could you not use OrderBy -> ThenBy?

http://msdn.microsoft.com/en-us/library/bb534743.aspx

mwilson
While this should work, this is not what the OP asked. He wants to know what he is doing wrong with his approach (i.e. Why is using a Comparer not working)
Miky Dinescu
+1  A: 

This should work better:

class PointComparer : IComparer<Point>
{
  public int Compare(Point first, Point second)
  {
    if (first.X == second.X)
    {
        return first.Y - second.Y;
    }
    else
    {
        return first.X - second.X;
    }

  }
}

If the X values are different, it will use the Y value for sorting. This is different from your code, where X values will be used if the Y values are the same.

As others have mentioned, if you can use Linq, you should use the OrderBy and ThenBy extension methods:

pointsList.OrderBy(p => p.X).ThenBy(p => p.y)
Oded
Thx. but no luck, the original order stays unchanged.
Mikos
this is almost the same as he had, except yours has a typo "first.X == first.X"... that is always true, so the else would never hit
Miky Dinescu
thx @miky, that did it! phew!
Mikos
@Miky D - thanks for the correction :)
Oded
A: 

Why not:

var sorted = pointsList.OrderBy(p => p.X)
                       .ThenBy(p => p.y)
tzaman
While this should work, this is not what the OP asked. He wants to know what he is doing wrong with his approach (i.e. Why is using a Comparer not working)
Miky Dinescu