Generic List.Sort

I often want to use a list to sort and every time I have to go searching on how to use the IComparer interface.

Assume I have a Person object with the “DisplayName” property that I wish to sort by.

I created the following class:

public class PersonDisplayNameAscendingComparer : IComparer
{
    #region IComparer Members

    public int Compare(Person x, Person y)
    {
        return x.DisplayName.CompareTo(y.DisplayName);
    }

    #endregion
}

And then assuming you have a List called people, you can sort like this;

    PersonDisplayNameAscendingComparer personComparer = new PersonDisplayNameAscendingComparer();
    people.Sort(personComparer);

Job done.