2016-02-07 46 views
-2

所以這裏是協議:我從我的同事那裏得到了一個代碼,他無法弄清楚他犯的錯誤。他想先按Y排序數組,然後按X(如果Y = Y)排序。你能幫我嗎?排序數組中的二維點...我錯過了什麼?

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