public static List<Node<T>> CreateTree<T>(List<T> flatDataObject, Func<T, bool> IsRootNode) where T : IDbEntityNode
{
var lookup = new Dictionary<int, Node<T>>();
var rootNodes = new List<Node<T>>();
foreach (T element in flatDataObject)
{
if (!lookup.TryGetValue(element.Id, out Node<T> currentNode))
{
currentNode.Value = element;
}
else
{
currentNode = new Node<T>() { Value = element };
lookup.Add(element.Id, currentNode);
}
if (IsRootNode(element))
{
rootNodes.Add(currentNode);
}
else
{
if (!lookup.TryGetValue(element.ParentId, out Node<T> parentNode))
{
parentNode = new Node<T>();
lookup.Add(element.ParentId, parentNode);
}
parentNode.Children.Add(currentNode);
currentNode.Parent = parentNode;
}
}
return rootNodes;
}
Here the for
-loop is changed to a foreach
-loop which makes it a little more readable.
The first lookup.TryGetValue()
:
if (lookup.TryGetValue(flatDataObject[element].Id, out currentNode))
{
currentNode.NodeInformation = flatDataObject[element];
}
else
{
currentNode = new GenericNode<T>() { NodeInformation = flatDataObject[element] };
lookup.Add(flatDataObject[element].Id, currentNode);
}
is negated because if the node is found in lookup there's no need to set NodeInformation
again.