递归之无限极评论

public ActionResult Index()
        {

            TestEntities tn = new TestEntities();

            List lylist =  tn.ly.ToList();

            //ViewBag.lyparent = lylist.Where(a => a.ParentId == null).ToList();

           // ViewBag.alllist = lylist;

            List mtn = ParseTree(lylist);

            ViewBag.alllist = mtn;

            return View();
        }

 
  
/// 
        /// 解析成一个树的结构
        /// 
        /// 
        public List ParseTree(List lylist) 
        {
            List mytn = new List();

            //第一步:先把根节点拿到
            foreach (ly item in lylist.Where(a=>a.ParentId==null))
            {
                MyTreeNode myn = new MyTreeNode();
                myn.content = item;

                myn.level = 1;

                mytn.Add(myn);
            }

            //第二步:为每个子节点找到对应的父亲
            foreach (ly item in lylist.Where(a=>a.ParentId!=null))
            {
                FindParent(mytn,item);
            }


            return mytn;
        }

        /// 
        /// 为每个子节点找到对应的父亲
        /// 
        /// 
        /// 
        public void FindParent(List _mytn, ly _item) 
        {
            foreach (MyTreeNode item in _mytn)
            {
                if (item.content.Id == _item.ParentId) //表示父亲已经找到了 
                {
                    if (item.child == null)
                    {
                        item.child = new List();
                    }

                    MyTreeNode node = new MyTreeNode();
                    node.content = _item;

                    node.level = item.level + 1;

                    item.child.Add(node);

                    return;
                }

                //如果该节点还有子节点,继续找
                if (item.child != null) 
                {
                    FindParent(item.child, _item);
                }

            }
        }

    }

    public class MyTreeNode
    {
        public ly content { get; set; }

        public int level { get; set; }

        public List child { get; set; }
    }
}




前台代码

@{
   
    List alllist = ViewBag.alllist as List;

    @parseTree(alllist);
}


@helper parseTree(List alllist)
{
    
    foreach (MyTreeNode item in alllist)
    {
            
@item.content.Content
if(item.child!=null) { @parseTree(item.child); } } }


 
  

你可能感兴趣的:(.net)