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