c#通用递归生成无限层级树
2015-12-07 19:52
507 查看
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);
原文地址:http://www.cnblogs.com/xuejianxiyang/p/5027280.html
相关文章推荐
- C#特性详解
- 造轮子:C#中将图片转化成base64字符串
- c#获取当前月的第一天和最后一天
- C# Mvc中文件下载
- C#遍历类的属性 PropertyInfo.Attributes
- c# 动态操作 zip\rar 文件,压缩解压组件使用
- c#如何将winform窗体封装成可以引用的dll文件
- C#使用事务
- C#邮箱发送验证码
- C#实现简单聊天程序的方法
- C#邮箱发送
- C#类型转换总结(三)各类型转化实例
- C# 八进制数值字符串转换成ASCII 字符串相互转换
- C# 操作自定义config文件
- c#生成时间戳
- C# 函数中的out型参数
- C#模拟windows账户登录,并复制文件代码
- c#之时间戳与DateTime的相互转换
- c#读取excel的xls和xlsx文件的方法
- C#.net 数据操作--excel 操作类