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.