Friday, December 5, 2008

Quick and Dirty Object Sorting by Implementing IComparer<T>

Let's say you have a simple Person class with some properties of First Name and Last Name. You then populate them into a strongly typed List<T> and would like to sort them by Last Name. Fortunately there is a very easy solution.

1. Create a Person class:

public class Person
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public Person

2. Create a PersonComparer class that implements IComparer<Person>:

public class PersonComparer : IComparer<Person>
    public int Compare(Person p1, Person p2)
        return String.Compare(p1.LastName, p2.LastName);

3. It was that easy. Now write some test code:

static void Main(string[] args)
    List<Person> personList = new List<Person>();
        personList.Add(new Person { FirstName = "George", LastName = "Washington"});
        personList.Add(new Person { FirstName = "Abraham", LastName = "Lincoln" });
        personList.Add(new Person { FirstName = "John", LastName = "Adams" });
        personList.Sort(new PersonComparer()); //Or use alternative below
        foreach (Person p in personList)
            Console.WriteLine("{0}, {1}", p.LastName, p.FirstName);

Alternative: If you need a one off, create a delegate that will sort the object on the fly. You will not need to implement the PersonComparer class, however it is not as reusable.

personList.Sort(delegate(Person p1, Person p2)
    return p1.LastName.CompareTo(p2.LastName);

No comments:

Post a Comment