struct MyPoint: IComparable { private int _x; private int _y; public int X { get { return this._x; } } public int Y { get { return this._y; } } public MyPoint(int x, int y) { this._x = x; this._y = y; } #region IComparable Members public int CompareTo(object obj) { if (obj is MyPoint) { MyPoint other = (MyPoint)obj; if (this._x.CompareTo(other.X) == 0) { return this._y.CompareTo(other.Y); } else { return this._x.CompareTo(other.X); } } else { throw new NotSupportedException("obj is not a MyPoint"); } } #endregion }
List<MyPoint> list = new List<MyPoint>(); list.Add(new MyPoint(10, 5)); list.Add(new MyPoint(10, 2)); list.Add(new MyPoint(10, 3)); list.Add(new MyPoint(4, 1)); list.Add(new MyPoint(15, 1)); list.Sort(); foreach (MyPoint p in list) { Console.WriteLine(p); } /* Will Print: (4, 1) (10, 2) (10, 3) (10, 5) (15, 1) */