Sort points vertically, then horizontally
No, you cannot just sort twice, because the .Net framework Sort () sorting algorithm is unstable, which means that when you sort the items, the order in which they were original is not taken into account, that is, when two items are equal, their position relative to each other will be undefined.
What you need to do is implement a custom IComparer for the class you are trying to sort and use for comparison when sorting your collection:
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;
}
}
}
Using:
List<Point> list = ...;
list.Sort(new PointComparer());
source to share
I can't tell from the question if by "sort both vertically and horizontally" you want to sort them "first vertically then horizontally" (best done in one pass as other answers have said), or if you want to sort them so that the adjacent points in the plane are usually in the list. If it is the latter, there is a curve filling gap , which can be much better than a pure approach with vertical and then horizontal.
source to share