C# 构建动态树

 public class Tree
    {
        public Guid Id { get; set; }
        public string Url { get; set; }
        public Guid? ParentId { get; set; }
        public string MenuName { get; set; }
    }
        public static string GetTree(IList<Tree> treeList, Guid? parentId, string name)
        {
            string menuName = "";
            List<Tree> treeMenu = treeMenu = treeList.Where(o => o.ParentId == parentId).ToList();


            if (parentId != null)
            {
                menuName = treeList.SingleOrDefault(o => o.Id == parentId).MenuName.ToString();
            }
            if (treeMenu.Count > 0)
            {
                string html = (parentId == null ? "" : String.Format("<a>{0}</a>", name)) + "<ul>";
                foreach (var item in treeMenu)
                {
                    string tmp = GetTree(treeList, item.Id, item.MenuName);
                    html += String.Format("<li>{0}</li>", tmp);
                }
                html += "</ul>";
                return html;
            }
            else
            {
                return string.Format("<li>最子级节点:{0}</li>", menuName);
            }
        }
 List<Tree> treeList = new List<Tree> 
            {
                new Tree{ Id=Guid.Parse("267f843a-685d-48ee-aa74-a383fd104320"),ParentId=null,MenuName="商户管理",Url="/Home"},
                new Tree{ Id=Guid.Parse("dc8bfae4-ad6f-48ac-878b-62174d5f7ca1"),ParentId=Guid.Parse("267f843a-685d-48ee-aa74-a383fd104320"),MenuName="商户信息",Url="/User"},
                new Tree{ Id=Guid.Parse("3f090619-ce8b-4995-8455-bbafb70f60f3"),ParentId=Guid.Parse("dc8bfae4-ad6f-48ac-878b-62174d5f7ca1"),MenuName="添加用户",Url="/User/Add"},
                  new Tree{ Id=Guid.Parse("417bbebf-35da-4c7d-9610-6598d2a2cba4"),ParentId=Guid.Parse("dc8bfae4-ad6f-48ac-878b-62174d5f7ca1"),MenuName="删除用户",Url="/User/Del"},
                   new Tree{ Id=Guid.Parse("05adfa1c-f2f8-46fc-89bb-8519be2bca62"),ParentId=Guid.Parse("dc8bfae4-ad6f-48ac-878b-62174d5f7ca1"),MenuName="查询用户",Url="/User/Sel"},
                    new Tree{ Id=Guid.Parse("66576099-947e-44f0-86dc-921827e48307"),ParentId=Guid.Parse("dc8bfae4-ad6f-48ac-878b-62174d5f7ca1"),MenuName="修改用户",Url="/User/Edit"},
            };
            Console.WriteLine(GetTree(treeList, null, ""));

 

posted @ 2016-03-14 11:33  the boy、图样图森破  阅读(1007)  评论(0编辑  收藏  举报