递归构建层级树

  class Program
    {
        static void Main()
        {
            List<MyClass> result = new List<MyClass>();
            result.Add(new MyClass() { DisplayName = "新余", Key = 3, Owner = 1 });
            result.Add(new MyClass() { DisplayName = "宜春", Key = 4, Owner = 1 });
            result.Add(new MyClass() { DisplayName = "杭州", Key = 5, Owner = 2 });
            result.Add(new MyClass() { DisplayName = "义乌", Key = 6, Owner = 2 });
            result.Add(new MyClass() { DisplayName = "江西", Key = 1, Owner = 0 });
            result.Add(new MyClass() { DisplayName = "浙江", Key = 2, Owner = 0 });
         


            var root = new HierarchyObject<MyClass>() { Data = new MyClass() { DisplayName = "Root", Key = 0 } };
            BuildTree(null, root, result);

        }

        public static void BuildTree(HierarchyObject<MyClass> parentNode, HierarchyObject<MyClass> root, List<MyClass> list)
        {
            var parentsIntheList = new List<MyClass>();
            foreach (var item in list)
            {
                if (list.All(li => li.Key != item.Owner && item.Owner != 0))//if a node whose parent not in the list, then we all so add it to the node
                    parentsIntheList.Add(item);
            }
            int parentId = parentNode == null ? 0 : parentNode.Data.Key;
            var filterdList = list.FindAll(item => item.Owner == parentId);
            if (parentNode == null)
            {
                filterdList.AddRange(parentsIntheList);
            }

            foreach (var item in filterdList)
            {
                var node = new HierarchyObject<MyClass> { Data = item };
                if (parentNode == null)//only the first level
                {
                    root.Children.Add(node);
                    BuildTree(node, root, list);
                }
                else
                {
                    parentNode.Children.Add(node);
                    BuildTree(node, root, list);
                }
            }
        }
    }
}
 public class MyClass : INodeInfomation
    {
        public string DisplayName { get; set; }
        public string Path { get; set; }
        public int Owner { get; set; }
        public int Key { get; set; }
    }

 思路:

从父节点出发,只有第一层的节点比较特殊,它们需要直接加到根节点之上,除此之外,所有的节点的都是加在当节点的下面的。

posted @ 2013-05-29 07:52  chunchill  阅读(1525)  评论(0编辑  收藏  举报