Generalizing constructors to operate on arrays in C#
arrays, c#
Solution
Some LINQ will do the trick:
TreeNode[] animalNodes = animals.Select(a => new TreeNode(a)).ToArray();
The `Select` extension method executes the specified delegate (specified via a lambda here) on each member of the list, and creates a list of the results (`IEnumerable<TreeNode>` in this case). The `ToArray` extension method is then used to create an array from the result.
Alternatively, you can use LINQ's query syntax:
TreeNode[] animalNodes = (from a in animals select new TreeNode(a)).ToArray();
The code generated by the compiler is the same for both these examples.
Problem
I wanted to know how to apply a constructor on each element of an array that would then return an array of constructed objects. Specifically, I am working with C#'s `TreeNode`. The concept I want is as follows: ``` string[] animals = {"dog","cat","mouse"}; TreeNode[] animalNodes = TreeNode[](animals); ``` Where `TreeNode[](animals)` would have the cumulative effect of ``` animalNodes[0] = TreeNode("dog"); animalNodes[1] = TreeNode("cat"); animalNodes[2] = TreeNode("mouse"); ``` I know I can us `foreach` and load such a structure manually but if possible, I'm looking for the elegant 'one line' way. I have looked long and hard for how to do this but could not find anything.