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

王朝学院·作者佚名  2016-08-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

NewsType结构:

Id

ParentId

Name

children(List<NewsType>)

publicvoidLoopToAppendChildren(List<NewsType>all, NewsType curItem)

{var subItems = all.Where(ee => ee.ParentId==curItem.Id).ToList();curItem.children =newList<NewsType>();

curItem.children.AddRange(subItems);foreach(varsubIteminsubItems)

{

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 =newNewsType();

rootRoot.Id=0;

rootRoot.ParentId=0;

rootRoot.Name="根节点";

LoopToAppendChildren(dc.NewsType.ToList(), rootRoot);

[flash=500,400]http://s1.knowsky.com/20160211/qxzyc4lrv4v21.png[/flash]

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航