Sort a list of 2D points (X first, then Y)
I am trying to sort a list of 2D points first by the x coordinate and then by the y coordinate. I have 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 sort like this:
pointsList.Sort(new PointComparer());
For some reason, the list is not sorted. This is probably something very simple and stupid, but has been stuck on this for quite a long time. TIA
+2
a source to share
3 answers
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 the X values will be used if the Y values are the same.
As mentioned, if you can use Linq, you should use extension methods OrderBy
and ThenBy
:
pointsList.OrderBy(p => p.X).ThenBy(p => p.y)
+6
a source to share