[Solved] Foreach loop in LINQ without loop


Treating this as a kind of code-golf, the following gives an idea as to how you can approach the problem from a functional mindset, where you try and ‘flow’ the results of one function through another (which is presumably what your manager is after).

Some changes are possible:

  • Replacing the if with a filter predicate on the set
  • By changing the recursive method AddNodes() to return the node, it can be used in a fluent style.

There also an obvious design mismatch given that TreeViews weren’t designed with FP in mind, and instead encourage iterative mutation to the tree to build it up.
Sadly, TreeNodeCollection has no direct setter, nor an AddRange. So the horrid ForEach mutation seems necessary.

As a result, it is moot whether this constitutes any kind of improvement to your imperative original solution (Unless the rest of your code base is maintained by a bunch of F# or Haskell programmers). A TreeView which can be constructed in one projection would IMO be a pre-requisite for the switch to this approach.

// Recursive Funcs need to be forward-declared
Func<DirectoryEntry, TreeNode, TreeNode> addNodes = null;
addNodes = (entry, node) =>
    {
        entry.Children
           .Cast<DirectoryEntry>()
           .ToList() // Needed for ForEach
           .ForEach(
             child =>
               node.ChildNodes.Add(
                     addNodes(child,
                    new TreeNode(child.Name.Substring(child.Name.IndexOf('=') + 1)))));
        return node;
    };

OUs.Where(ou => ou.SchemaClassName.Contains("organizationalUnit"))
    .ToList()
    .ForEach(ou =>
            rootNode.ChildNodes.Add(addNodes(ou, 
                 new TreeNode(ou.Name.Substring(ou.Name.IndexOf('=') + 1)))));
treeView1.Nodes.Add(rootNode);

2

solved Foreach loop in LINQ without loop