Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / sorting

Sorting Lists Using an Anonymous Delegate

0.00/5 (No votes)
14 Feb 2011CPOL 12.3K  
Sorting Lists Using an Anonymous Delegate
I was writing a method to add Nodes to a TreeView.

The nodes at different levels represented different types of data, each type was implemented as a lightweight class. Because I wanted to make adding the nodes as simple as possible I had overridden the ToString() method of each to return the text as I wanted it to appear in the TreeView.

I decided that it would be easiest to write one method that could add any of the classes I intended to use and the obvious way to do that was to write a Generic Method and pass it the parent node and a list of items to be added to the parent.

All went well until I noticed that the nodes were unsorted. I quickly added
C#
nodeData.Sort();

and of course this raised an InvalidOperationException

"Failed to compare two elements in the array."


I started to edit my classes to make them implement IComparable but there were a lot of them and it occurred to me that this would be a good use of an Anonymous Delegate.

Here is an abbreviated version of the method concerned:
C#
private bool FillNode<T>(TreeNode aNode, List<T> nodeData)
{
    bool result = false;
    this.myTreeView.BeginUpdate();
    try
    {
        // If aNode just has a 'Dummy' node, delete it.
        if ((aNode.Nodes.Count == 1) && string.IsNullOrEmpty(aNode.Nodes[0].Name))
        {
            aNode.Nodes.Clear();
        }

        // ************************************** 
        // Use an Anonymous Delegate to sort
        nodeData.Sort((a, b) => a.ToString().CompareTo(b.ToString()));
        // ************************************** 

        foreach (T ad in nodeData)
        {
            TreeNode newNode = new TreeNode(ad.ToString());
            newNode.Tag = ad;
            // Nodes at level 5 are leaf nodes and do not require the '+'
            if (aNode.Level < 5)
            {
                newNode.Nodes.Add("");      // Add a dummy node to force the + to appear.
            }
            aNode.Nodes.Add(newNode);
        }
        result = true;
    }
    finally
    {
        this.myTreeView.EndUpdate();
    }
    return result;
}


This was made easier because I had already overridden the ToString() method.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)