Implementation of the IComparable Interface in Two String Fields

How to implement IComparable interface in two string fields?

Use the example of the Person class below. If Person objects are added to the list. How to sort a list by last name first THEN Forename?

Class Person { public string Surname { get; set; } public string Forname { get; set; } } 

Something like?

 myPersonList.Sort(delegate(Person p1, Person p2) { return p1.Surname.CompareTo(p2. Surname); }); 
+6
c # compare
source share
2 answers

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 
+9
source share

Try it?

 int surnameComparison = p1.Surname.CompareTo(p2.Surname); if (surnameComparison <> 0) return surnameComparison; else return p1.Forename.CompareTo(p2.Forename); 
+1
source share

All Articles