Recent Articles

Quickly Sort A Collection Using Generics and Anonymous Delegate

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
     {
         Name,
         Email
     }
     #endregion

     #region Fields
     private SortType currentType = SortType.Name;
     #endregion

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

     #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;
     }
     #endregion
}

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.