By using `FirstOrDefault()` we can get the `root` node very easily and should remove it from the nodes collection. Let us introduce a method to do this
private static TreeNode RemoveRootNode(this List<TreeNode> nodes)
{
if (nodes == null)
{
throw new NullReferenceException("nodes");
}
var root = nodes.FirstOrDefault(n => !n.Parent.HasValue);
if (root != null)
{
nodes.Remove(root);
}
return root;
}
Now we don't need the root node to be the first item in the collection anymore.
Next we need the "main" method which takes a List<TreeNode> as a parameter and returns a TreeNode which is the root node like so
public static TreeNode BuildTree(this List<TreeNode> nodes)
{
var root = nodes.RemoveRootNode();
if (root == null) { throw new ArgumentOutOfRangeException("nodes"); }
return root.BuildTree(nodes);
}
###Edit By usingBased on the changed example data, we now can have multiple FirstOrDefault()TreeNode we can get thewith rootParent == null node very easily and should remove it fromwhich makes the nodes collection. Let us introduce aRemoveRootNode() method to do thissuperflous and will result in TreeNode buildTree(this List<TreeNode> like so
privatepublic static TreeNode RemoveRootNodeBuildTree(this List<TreeNode> nodes)
{
if (nodes == null)
{
throw new NullReferenceExceptionArgumentNullException("nodes");
}
var root = nodes.FirstOrDefault(n => !n.Parent.HasValue);
if (root != null)
{
nodes.Remove(root);
}
return root;
}
Now we don't need the root node to be the first item in the collection anymore.
Next we need the "main" method which takes a List<TreeNode> as a parameter and returns a TreeNode which is the root node like so
public static TreeNode BuildTree(this List<TreeNode> nodes)
{
var root = nodes.RemoveRootNode();
if (root == null) { throw new ArgumentOutOfRangeExceptionTreeNode("nodes"); }
return root.BuildTree(nodes);
}