可以使用实现比较接口的方法,直接用sort排序。
如c#:
class Person1:IComparable<Person1> { public string Xm { get; set; } public int Nl { get; set; } public int CompareTo(Person1 obj) { return Nl - obj.Nl; } }
主程序:
var a = new List<Person1>(); a.Add(new Person1() { Xm = "d", Nl = 20 }); a.Add(new Person1() { Xm = "c", Nl = 40 }); a.Add(new Person1() { Xm = "b", Nl = 10 }); a.Add(new Person1() { Xm = "a", Nl = 30 }); a.Sort(); foreach (var item in a) { Console.Write($"Name:{item.Xm},Age:{item.Nl}\t"); }
运行结果:
---------------------------------------------------------
对于java:
public class Person1 implements Comparable<Person1> { public String Xm; public int Nl; public Person1(String x,int y) { Xm=x; Nl=y; } public int compareTo(Person1 obj) { return Nl - obj.Nl; } }
主程序:
public static void main(String[] args) throws Exception { var a = new ArrayList<Person1>(); a.add(new Person1("d",20)); a.add(new Person1("c",40)); a.add(new Person1("b",10)); a.add(new Person1("a",30)); a.sort(Comparator.naturalOrder());//升序 for (Person1 item : a) { System.out.print("Name:"+item.Xm+",Age:"+item.Nl+"\t"); } }
运行结果:
c#还可以用lamda表达式指定比较器方法,排序:
Person1类:
主程序:
运行结果:
JAVA也有类似方法,此处略。