码迷,mamicode.com
首页 > Windows程序 > 详细

C# 构建动态树

时间:2016-03-14 12:15:01      阅读:403      评论:0      收藏:0      [点我收藏+]

标签:

 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, ""));

 

C# 构建动态树

标签:

原文地址:http://www.cnblogs.com/q975261413/p/5275101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!