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
This should work better:
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
OrderByandThenByextension methods: