#region 按类中的某个属性对类数组排序,尽量用JDK的类实现
public class EntityClass : IComparable
{
public int ID;
public string Name;
public int Age; public EntityClass(int id, string name, int age)
{
ID = id;
Name = name;
Age = age;
} public int CompareTo(object obj)
{
if (obj is EntityClass) {
EntityClass ec = obj as EntityClass;
if (this.Equals(ec)) return 0;
else if (ec.ID > this.ID) return -1;
else if (ec.Age > this.Age) return -1;
else return 1;
}
else throw new ArgumentException("object is not a Temperature");
}
} public class EntityClasses
{
public ArrayList al; public EntityClasses()
{
al = new ArrayList();
} public void Add(EntityClass ec)
{
al.Add(ec);
} public void Sort()
{
al.Sort();
} public void Print()
{
for (int i = 0; i < al.Count; i++)
{
EntityClass ec = al[i] as EntityClass; if (ec != null)
{
System.Console.Write(" Unit " + i.ToString() + " ID-" + ec.ID.ToString() + " Name-" + ec.Name.ToString() + " Age-" + ec.Age.ToString());
System.Console.WriteLine();
}
else {
System.Console.WriteLine(" Unit " + i.ToString() + " is null.");
}
}
}
}
#endregion
public class EntityClass : IComparable
{
public int ID;
public string Name;
public int Age; public EntityClass(int id, string name, int age)
{
ID = id;
Name = name;
Age = age;
} public int CompareTo(object obj)
{
if (obj is EntityClass) {
EntityClass ec = obj as EntityClass;
if (this.Equals(ec)) return 0;
else if (ec.ID > this.ID) return -1;
else if (ec.Age > this.Age) return -1;
else return 1;
}
else throw new ArgumentException("object is not a Temperature");
}
} public class EntityClasses
{
public ArrayList al; public EntityClasses()
{
al = new ArrayList();
} public void Add(EntityClass ec)
{
al.Add(ec);
} public void Sort()
{
al.Sort();
} public void Print()
{
for (int i = 0; i < al.Count; i++)
{
EntityClass ec = al[i] as EntityClass; if (ec != null)
{
System.Console.Write(" Unit " + i.ToString() + " ID-" + ec.ID.ToString() + " Name-" + ec.Name.ToString() + " Age-" + ec.Age.ToString());
System.Console.WriteLine();
}
else {
System.Console.WriteLine(" Unit " + i.ToString() + " is null.");
}
}
}
}
#endregion
public int CompareTo(object obj)
{
if (obj is EntityClass) {
EntityClass ec = obj as EntityClass;
if (this.Equals(ec)) return 0;
else if (ec.ID > this.ID) return -1;
else if (ec.Age > this.Age) return -1;
else return 1;
}
else throw new ArgumentException("object is not a Temperature");
}
好象是没有意义.
else if (ec.Age > this.Age) return -1;先用ID从小到大排,如果ID相同,就按年龄从小到大摆.
它用的就是快速排序法,CompareTo就是两较两个类的方法咯.