# Sorting a list of points

• ### Question

• User-680512290 posted
Hi I need to sort a list of System.Drawing.Point[] quickly by x, then y. Can anyone point me in the direction of some code? Thanks in advance GW
Monday, March 14, 2005 12:33 PM

### All replies

• User-680512290 posted
Thanks for all the replies! Heres what I came up with - it might help someone one day. Build a list of points like this: ArrayList list = new ArrayList(); // add a few if these System.Drawing.Point pnt = new System.Drawing.Point(100,100); list.Add(new SortedPoint(pnt)); // Sort the list of points by increasing (x, y) list.Sort(new LinkedPointComparer()); // and here is the class... using System; using System.Collections; using System.Drawing; using System.Reflection; class SortedPoint { private int _x; private int _y; public SortedPoint(System.Drawing.Point p) { this.X = p.X; this.Y = p.Y; } public int X { get { return _x; } set { _x = value; } } public int Y { get { return _y; } set { _y = value; } } } public class SortedPointComparer : IComparer { public SortedPointComparer() : base() { } int IComparer.Compare(object a, object b) { SortedPoint pA = (SortedPoint) a; SortedPoint pB = (SortedPoint) b; if (pA.X == pB.X) { // consider y coordinate then if (pA.Y > pB.Y) return 1; if (pA.Y < pB.Y) return -1; // x and y are the same return 0; } if (pA.X > pB.X) return 1; if (pA.X < pB.X) return -1; return 0; } }
Tuesday, March 22, 2005 11:13 AM