Nov 13 2006

Sorting .NET 2.0 collection using anonymous methods

Posted by admin under .NET 2.0

Instead of creating a comparer class as described here it is possible to do typesafe sorting using anonymous methods.

While it has taken me a while to get used to the syntax I now really like this technique.

Consider this example, we have a class DivisionPartCollection - which derives from System.Collections.Generic.List<DivisionPart> and therefore implements a typesafe collection of "DivisionPart"s.

The DivisionPart class has a property "Year" and we want to provide a method "SortOnYear" in the list class which should sort the collection items on year.



    public class DivisionPartCollection : System.Collections.Generic.List<DivisionPart>
    {
        public void SortOnYear()
        {
            Sort(delegate(DivisionPart oPart1, DivisionPart oPart2)
                {
                    return oPart1.Year.CompareTo(oPart2.Year);
                }
            );

        }

By using the delegate keyword we can create an inline function directly to feed to the inherited Sort method.