Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing the IComparable Interface on two string fields

Tags:

c#

compare

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);
});
like image 655
CSharpeANdJavaGuy123 Avatar asked Oct 06 '09 12:10

CSharpeANdJavaGuy123


2 Answers

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
like image 96
Drew Noakes Avatar answered Sep 19 '22 21:09

Drew Noakes


Try this?

int surnameComparison = p1.Surname.CompareTo(p2.Surname);

if (surnameComparison <> 0)
  return surnameComparison;
else
  return p1.Forename.CompareTo(p2.Forename);
like image 36
Lennaert Avatar answered Sep 18 '22 21:09

Lennaert