Home > c# > Generic List.Sort

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.

Categories: c#
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: