2016-02-07 5 views
-2

Итак, вот сделка: у меня есть код от моего коллеги, который не может понять ошибки, которые он совершил. Он хотел сначала отсортировать массив по Y, затем по X (если Y = Y). Вы можете помочь?Сортировка 2D-точек в массиве ... что мне не хватает?

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(); 
} 
} 

Любые идеи?

ответ

0

Вы можете попробовать:

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; 
    } 
}); 
0

Вы могли бы реализовать ICompareable и добавьте следующий код:

точки общественного класса: 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"); 
    }