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:
[csharp]
public class PersonDisplayNameAscendingComparer : IComparer
{
#region IComparer Members

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

#endregion
}
[/csharp]

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

[csharp]
PersonDisplayNameAscendingComparer personComparer = new PersonDisplayNameAscendingComparer();
people.Sort(personComparer);
[/csharp]

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.