Friday, January 8, 2010

Get TreeNode from Full Path in Winform

This is a recursive method that finds a TreeNode in a .NET TreeView control from its full path.

public TreeNode GetNodeFromPath(TreeNode node, string path)
        {
        TreeNode foundNode = null;
        foreach (TreeNode tn in node.Nodes)
        {
            if (tn.FullPath == path)
            {                 
                return tn;
            }
            else if (tn.Nodes.Count > 0)
            {
                foundNode = GetNodeFromPath(tn, path);
            }
            if (foundNode != null)
                return foundNode;
        }
        return null;
        }


Thursday, January 7, 2010

List and ForEach

Let's say you have a List of strings in C# and you add each element of the List to a StringBuilder.

StringBuilder sb = new StringBuilder();
List  <string> list = new List <string>();
list.add("one");
list.add("two");
list.add("three");

You could do the following loop:

foreach(var item in list){
  sb.Append(item); 
}
An alternative method to achieve the same functionality would go like this:
list.ForEach(item =>sb.Append(item));

With this method you save 2 lines of code and improve readability.