How do I implement the IComparable Interface on two string fields?
Using the Person class example below. If Person objects are added to a list. How do I sort the list based on Surname 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);
});
Or you could sort a list like this:
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 could have Person
implement IComparable<Person>
with 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 commented, you might decide you need to check for nulls. If so, you should decide whether nulls should be sorted to the top or bottom. Something like this:
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
Try this?
int surnameComparison = p1.Surname.CompareTo(p2.Surname);
if (surnameComparison <> 0)
return surnameComparison;
else
return p1.Forename.CompareTo(p2.Forename);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With