所以这是交易:我从我的同事那里得到了一个代码,他无法弄清楚他犯的错误。他想先用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 :(得分: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;
}
});
答案 1 :(得分:0)
您可以实现ICompareable并添加以下代码:
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");
}