Or you can sort the list as follows:
myPersonList.Sort(delegate(Person p1, Person p2) { int result = p1.Surname.CompareTo(p2.Surname); if (result == 0) result = p1.Forname.CompareTo(p2.Forname); return result; });
Alternatively, you can implement Person IComparable<Person> using this method:
public int CompareTo(Person other) { int result = this.Surname.CompareTo(other.Surname); if (result == 0) result = this.Forname.CompareTo(other.Forname); return result; }
EDIT . As Mark pointed out, you can decide that you need to check for zeros. If so, you must decide whether to sort the zeros at the top or bottom. Something like that:
if (p1==null && p2==null) return 0; // same if (p1==null ^ p2==null) return p1==null ? 1 : -1; // reverse this to control ordering of nulls
Drew noakes
source share