65.9K
CodeProject is changing. Read more.
Home

Sorting Lists Using an Anonymous Delegate

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 14, 2011

CPOL
viewsIcon

12280

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
  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:
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.