Quickly Sort A Collection Using Generics and Anonymous Delegate

Location: BlogsRevindex.NET    
Posted by: revindex 8/2/2007 12:36 AM

One nice enhancement that came with .NET 2.0 is the ability to sort a custom collection quickly by making use of anonymous delegates and generics.

In the past on .NET 1.1, you had to create a Comparer class implementing the IComparer interface like the one below before passing it to the Sort method.

public class ProfileComparer : IComparer
     #region Enums
     public enum SortType

     #region Fields
     private SortType currentType = SortType.Name;

     #region Constructors
     public FreeReportComparer() : base() { }
     public FreeReportComparer(SortType type) : base()
         currentType = type;

     #region Methods
     int IComparer.Compare(object a, object b)

         Profile x = (Profile) a;
         Profile y = (Profile) b;

         if (currentType == SortType.Name)
             return x.Name.CompareTo(y.Name);
         else if (currentType == SortType.Email)
             return x.Email.CompareTo(y.Email);

         return 0;

If you make use of the new generic List<> collection in 2.0, you can have strong type and the easy sort altogether. Suppose you create a List<> collection of Profile objects.

List<Profile> profiles = new List<Profile>();
profiles.Add(new Profile("John", "john@example.com"));
profiles.Add(new Profile("Andrew", "andrew@example.com"));

To sort by Name is as easy as writing this a one-line code. Notice we didn't have to implement the IComparer class. That's because anonymous delegate allows the compiler to create an instance method without needing to wrap it in a class.

profile.Sort(delegate(Profile a, Profile b) {
         return a.Name.CompareTo(b.Name);

If we want to sort by Email, we can easily do it like this.

profile.Sort(delegate(Profile a, Profile b) {
         return a.Email.CompareTo(b.Email);

If you still have custom collections based on CollectionBase, you really want to take the time to migrate them over to generics and gain some efficiency in your work. It's worth the effort and makes your code more maintanable.

Permalink |  Trackback

Comments (1)   Add Comment
Re: Quickly Sort A Collection Using Generics and Anonymous Delegate    By Thies on 10/11/2008 11:10 AM
In .Net 3.0 you can simplify even furthur using lambda expressions;

profiles.Sort((a, b) => a.Name.CompareTo(b.Name));

Thanks for the blog, cheers
- Thies (www.agile2go.com)

Your name:
Add Comment   Cancel