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);


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

    PersonDisplayNameAscendingComparer personComparer = new PersonDisplayNameAscendingComparer();

Job done.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.