using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Swarmops.Common.Interfaces; namespace Swarmops.Common.Generics { public class Tree where TNode: IHasIdentity, IHasParentIdentity { public Tree() { RootNodes = new List>(); this._nodeLookup = new Dictionary>(); } public List> RootNodes { get; private set; } private readonly Dictionary> _nodeLookup; public TreeNode this [int identity] { get { return this._nodeLookup[identity]; } } public static Tree FromCollection (List collection) { Dictionary>> parentLookup = new Dictionary>>(); Tree result = new Tree(); // To construct a tree from a random collection, start by keying all parent identities into a dictionary foreach (TNode item in collection) { TreeNode node = new TreeNode(item); if (!parentLookup.ContainsKey ((item.ParentIdentity))) { parentLookup[item.ParentIdentity] = new List>(); } parentLookup[item.ParentIdentity].Add (node); result._nodeLookup[item.Identity] = node; } // Then, recurse into that dictionary, starting at parentId zero which becomes the root level result.RootNodes = ConstructRecurse (null, parentLookup); return result; } private static List> ConstructRecurse (TreeNode parent, Dictionary>> parentLookup) { List> result = new List>(); int nodeId = parent == null ? 0 : parent.Data.Identity; if (!parentLookup.ContainsKey (nodeId)) { return result; // no nodes with requested parent - exit condition hit, return empty list } foreach (TreeNode node in parentLookup[nodeId]) { node.Parent = parent; node.Children = ConstructRecurse (node, parentLookup); result.Add (node); } return result; } } public class TreeNode where TNode: IHasIdentity, IHasParentIdentity { public TreeNode() { Children = new List>(); } public TreeNode (TNode data) { Data = data; } public TNode Data; public List> Children; public TreeNode Parent; } }