Sep 27 2006

Sorting .NET 2.0 collection

Posted by admin under .NET 2.0

Please start by reading Part 1

Now lets add sorting. We want typesafe sorting just like in the .NET 1.x solution.

So while someone smarter than me probably could whip up a solution using generics more to the extreme, my solution for sorting my collections in .NET 2.0 uses the same technology as for 1.x:



public class LinkComparer : IComparer<Link>
{
    public enum SortingFields
    {
        Name,
        Url
    }
    public enum SortAscDesc
    {
        Asc,
        Desc
    }
    private SortingFields m_SortField;
    private SortAscDesc m_AscDesc;


    public LinkComparer(SortingFields sortField, SortAscDesc ascDesc)
    {
        m_SortField = sortField;
        m_AscDesc = ascDesc;
    }

    #region IComparer Members

    public int Compare(Link oLink1, Link oLink2)
    {
        int nRet = 0;
        if (m_SortField == SortingFields.Name)
            nRet = oLink1.Name.CompareTo(oLink2.Name);
        else if (m_SortField == SortingFields.Url)
            nRet = oLink1.Url.CompareTo(oLink2.Url);
        if (m_AscDesc == SortAscDesc.Desc)
            nRet = -nRet;
        return nRet;
    }

    #endregion
}


We create a custom LinkComparer class implementing the IComparer interface. The difference here is that the IComparer implementation is parameterized - typesafe. So since we derive from IComparer<Link> our Compare function can be made type safe as well:

public int Compare(Link oLink1, Link oLink2)

Now our collection class:



public class LinkCollection  : System.Collections.Generic.List<Link> 
{
    public void Sort(LinkComparer.SortingFields sortField, LinkComparer.SortAscDesc ascDesc)
    {
        base.Sort(new LinkComparer(sortField, ascDesc));
    }

}


We create an override implementation for Sort - and call the base sort passing in our LinkComparer object.

Which lets the GUI code looks something like this - for example:



    private LinkCollection GetCollList()
    {
        LinkCollection oColl = new LinkCollection();
        Link oNew = new Link();
        oNew.Name = "ASPCode";
        oNew.Url = "http://www.aspcode.net";
        oColl.Add(oNew);

        oNew = new Link();
        oNew.Name = "ASP.NET";
        oNew.Url = "http://www.asp.net";
        oColl.Add(oNew);

        oNew = new Link();
        oNew.Name = "411asp.net";
        oNew.Url = "http://www.411asp.net";
        oColl.Add(oNew);


        oColl.Sort(LinkComparer.SortingFields.Name, LinkComparer.SortAscDesc.Desc);

        return oColl;

    }