I have an array of Points and i want to sort then both vertically and horizontally.
Should I sort twice?
No you can't just sort twice because the .Net framework Sort() algorithm is an unstable sort, which means that when you sort items, the order they originaly were in is not taken into account, that is, when two items are equal, their position relative to each other will be undefined.
What you will need to do is implement a custom IComparer for the class you are trying to sort and use that comparer 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;
}
}
}
Usage:
List<Point> list = ...;
list.Sort(new PointComparer());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With