Sort a list of objects by implementing the IComparable interface in c#

In the following code sample, the person class extends the IComparable interface and the required CompareTo method and allows it to be sorted in a List generic collection using the person’s first and last name:
Person Class:

public class person : IComparable
{
    string firstName;
    string lastName;
    public person(string _firstName, string _lastName)
    {
        firstName = _firstName;
        lastName = _lastName;
    }
    override public string ToString()
    {
        return firstName + " " + lastName;
    }
public int CompareTo(object obj)
{
    person otherPerson = (person)obj;
    if (this.lastName != otherPerson.lastName)
    return this.lastName.CompareTo(otherPerson.lastName);
    else
    return this.firstName.CompareTo(otherPerson.firstName);
}
}

sorting the list of person objects

List<person> l = new List<person>();
l.Add(new person("item", "raja"));
l.Add(new person("Kaka", "biryani"));
l.Add(new person("Zues", "mahesh"));
l.Sort();
foreach (person p in l)
Console.WriteLine(p.ToString());

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.