Esempio n. 1
0
        /// <summary>
        /// 将关系数据列表 转化为 树状图
        /// </summary>
        /// <param name="parentId">根节点</param>
        /// <param name="relation">关系数据</param>
        /// <returns></returns>
        public Node GetRoot(int parentId, List<Mapping> mapping)
        {
            var root = new Node();
            root.Key = parentId;

            var groups = mapping.Select(x => new Node { Key = x.ChildID, Left = x.ParentID }).GroupBy(x => x.Left);
            var child = groups.FirstOrDefault(x => x.Key == parentId);

            if (child == null)
            {
                return null;
            }
            else
            {
                var children = child.ToList();
                if (children.Count > 0)
                {
                    var dict = groups.ToDictionary(g => g.Key, g => g.ToList());
                    for (int i = 0; i < children.Count; i++)
                    {
                        this.AddChild(children[i], dict);
                    }
                }

                root.Children = children;
            }

            return root;
        }
Esempio n. 2
0
 public void AddChild(Node child, IDictionary<int, List<Node>> mapping)
 {
     if (mapping != null && mapping.ContainsKey(child.Key))
     {
         child.Children = mapping[child.Key].ToList();
         for (int i = 0; i < child.Children.Count; i++)
         {
             this.AddChild(child.Children[i], mapping);
         }
     }
 }
Esempio n. 3
0
        public void PrintTree(Node node, string prefix)
        {
            Console.WriteLine("{0} + {1}", prefix, node.Key);
            if (node.Children == null)
            {
                return;
            }

            foreach (Node child in node.Children)
            {
                PrintTree(child, prefix + "    |");
            }
        }