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

c#通用递归生成无限层级树

时间:2015-12-07 20:45:16      阅读:2847      评论:0      收藏:0      [点我收藏+]

标签:

NewsType结构:

Id

ParentId

Name

children(List<NewsType>)

 

public void LoopToAppendChildren(List<NewsType> all,  NewsType curItem)
{
    var subItems = all.Where(ee => ee.ParentId==curItem.Id).ToList(); 
    curItem.children = new List<NewsType>();
    curItem.children.AddRange(subItems);
    foreach (var subItem in subItems)
    {
        LoopToAppendChildren(all, subItem);//新闻1.1
    }
}

 

//通用 ParentId,Id,children 用了反射效率不高

public void LoopToAppendChildren<T>(List<T> all, T curItem, string parentIdName = "ParentId", string idName = "Id", string childrenName = "children")
{
  var subItems = all.Where(ee => ee.GetType().GetProperty(parentIdName).GetValue(ee, null).ToString() == curItem.GetType().GetProperty(idName).GetValue(curItem, null).ToString()).ToList(); //新闻1

  curItem.GetType().GetField(childrenName).SetValue(curItem, subItems);
  foreach (var subItem in subItems)
  {
    LoopToAppendChildren(all, subItem);//新闻1.1
  }
 }


调用:
//实例化一个根节点 NewsType rootRoot = new NewsType(); rootRoot.Id = 0; rootRoot.ParentId = 0; rootRoot.Name="根节点"; LoopToAppendChildren(dc.NewsType.ToList(), rootRoot);

 

 

技术分享

c#通用递归生成无限层级树

标签:

原文地址:http://www.cnblogs.com/xuejianxiyang/p/5027280.html

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