-2

So here is the deal: I got a code from my colleague who cant figure out the mistakes he made. He wanted to sort the array first by Y, then by X (if Y=Y). Can you help?

using System;
using System.Collections;
public class Point {
 public int x;
 public int y;
 public Point(int x, int y) {
 x = x;
 y = y;
 }
 public string ToString() {
 return x + "," + y;
 }
}
public class PointList {

 public static void Main(string [] args) {
 ArrayList AL = new ArrayList();
 Random R = new Random();
 for (int i = 0; i < 10; i++) {
 Point p = new Point(R.Next(50), R.Next(50));
 AL.Add(p);
 }
 PrintValues(AL);
 AL.Sort();
 PrintValues(AL);
 }

public static void PrintValues( IEnumerable myList ) {
 foreach ( Object obj in myList )
 Console.WriteLine( "{0}", obj );
 Console.WriteLine();
 }
}

Any ideas?

2 Answers2

0

You can try with:

AL.Sort(delegate(Point a, Point b) {
    if (a.y < b.y ) return -1;
    else if (a.y > b.y ) return 1;
    else {
        if ( a.x < b.x ) return -1;
        else if ( a.x > b.x ) return 1;
        else return 0;
    }
});
Bob__
  • 12,361
  • 3
  • 28
  • 42
0

You could implement ICompareable and add the following code:

public class Point : IComparable

 public int CompareTo(object obj)
    {
        if (obj == null) return 1;

        Point otherPoint = obj as Point;
        if (otherPoint != null)
        {
            if(this.y == otherPoint.y)
            {
                return this.x.CompareTo(otherPoint.x);
            }
            return this.y.CompareTo(otherPoint.y);
        }

        else
            throw new ArgumentException("Object is not a Point");
    }
Kiksen
  • 1,559
  • 1
  • 18
  • 41