Array.sort 有3种方式:
class Person :IComparable<Person>{ private String firstname; public String Firstname { get { return firstname; } set { firstname = value; } } private String lastname; public String Lastname { get { return lastname; } set { lastname = value; } } public Person(String f,String l) { this.firstname = f; this.lastname = l; } public int CompareTo(Person other) { int result = this.Firstname.CompareTo(other.Firstname); if (result.Equals(0)) { result = this.Lastname.CompareTo(other.Lastname); } return result; } }
class util { public static int comp(Person p1,Person p2){ return p1.Lastname.CompareTo(p2.Lastname); } } Person p1 = new Person("san", "zhang"); Person p2 = new Person("si", "li"); Person p3 = new Person("wu", "wang"); Person[] a = { p3,p1,p2};
Array.Sort<Person>(a, new Comparison<Person>(util.comp));
或者
Array.Sort<Person>(a, (Person x, Person y) => { int r = x.Firstname.CompareTo(y.Firstname); if (r.Equals(0)) { r = x.Lastname.CompareTo(y.Lastname); } return r; });
class PersonComparer : IComparer<Person> { public int Compare(Person x, Person y) { int result = x.Lastname.CompareTo(y.Lastname); if (result.Equals(0)) { result = x.Firstname.CompareTo(y.Firstname); } return result; } } Person p1 = new Person("san", "zhang"); Person p2 = new Person("si", "li"); Person p3 = new Person("wu", "wang"); Person[] a = { p3,p1,p2}; Array.Sort<Person>(a,new PersonComparer());