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.
Some LINQ will do the trick:
The
Selectextension 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). TheToArrayextension method is then used to create an array from the result.Alternatively, you can use LINQ’s query syntax:
The code generated by the compiler is the same for both these examples.