C# 将List转成树的两种方式(递归、循环)
标签:ati htm stat tps parentId code temp 准备 div
背景
将一个具有ChildCode(子节点)和ParentCode(父节点)的list集合转换成树状结构。
生成数据基本格式,如下图:
最终展示样式,如下图:
(注:如果你对样式没要求,可以使用layui的树形组件,简单方便-https://www.layui.com/demo/tree.html)
有两种转换方式,一种是普通的递归,一种是双层循环。数据量非很大的情况下,递归的效率相比双层循环来说,效率高一些。
注:不要循环调用数据库,最好将数据根据条件全部查询出来,然后进行处理。
准备工作
声明一个Model类:
public class TreeNode
{
///
/// 子id
///
public string Id { get; set; }
///
/// 父id
///
public string ParentId { get; set; }
///
/// 名称
///
public string Name { get; set; }
///
/// 子节点
///
public List Children { get; set; }
///
/// 无参构造函数
///
public TreeNode()
{
Children = new List();
}
///
/// 有参构造函数
///
/// 子id
/// 名称
/// 父id
public TreeNode(string id, string name, string parentId)
{
this.Id = id;
this.Name = name;
this.ParentId = parentId;
Children = new List();
}
///
/// 有参构造函数
///
/// 子id
/// 名称
/// 父节点
public TreeNode(string id, string name, TreeNode parent)
{
this.Id = id;
this.Name = name;
this.ParentId = parent.Id;
Children = new List();
}
}
生成一个转换前的list集合:
TreeNode treeNode1 = new TreeNode("1", "山东", "0");
TreeNode treeNode2 = new TreeNode("2", "北京", "0");
TreeNode treeNode3 = new TreeNode("3", "历下区", treeNode1);
TreeNode treeNode4 = new TreeNode("4", "高新区", treeNode1);
TreeNode treeNode5 = new TreeNode("5", "历城区", treeNode1);
TreeNode treeNode6 = new TreeNode("6", "甸柳庄", treeNode3);
TreeNode treeNode7 = new TreeNode("7", "济南长途汽车站东站", treeNode6);
TreeNode treeNode8 = new TreeNode("8", "朝阳区", treeNode2);
TreeNode treeNode9 = new TreeNode("9", "海淀区", treeNode2);
TreeNode treeNode10 = new TreeNode("10", "金盏乡", treeNode8);
List list = new List();
list.Add(treeNode1);
list.Add(treeNode2);
list.Add(treeNode3);
list.Add(treeNode4);
list.Add(treeNode5);
list.Add(treeNode6);
list.Add(treeNode7);
list.Add(treeNode8);
list.Add(treeNode9);
list.Add(treeNode10);
递归方式
调用方式:
List trees1 = TreeHelper.BulidTreeByRecursive(list, new List(), "0");
实现代码:
///
/// 使用递归方法建树
///
public static List BulidTreeByRecursive(List treeNodes, List resps, string pID)
{
resps = new List();
List tempList = treeNodes.Where(c => c.ParentId == pID).ToList();
for (int i = 0; i )
{
TreeNode node = new TreeNode();
node.Id = tempList[i].Id;
node.ParentId = tempList[i].ParentId;
node.Name = tempList[i].Name;
node.Children = BulidTreeByRecursive(treeNodes, resps, node.Id);
resps.Add(node);
}
return resps;
}
双层循环
调用方式:
List trees = TreeHelper.BulidTree(list);
实现代码:
///
/// 双层循环
///
///
///
public static List BulidTree(List treeNodes)
{
try
{
List trees = new List();
foreach (var treeNode in treeNodes)
{
if ("0" == (treeNode.ParentId))
{
trees.Add(treeNode);
}
foreach (var it in treeNodes)
{
if (it.ParentId == treeNode.Id)
{
treeNode.Children.Add(it);
}
}
}
return trees;
}
catch (Exception ex)
{
throw ex;
}
}
代码下载
百度云盘:链接:https://pan.baidu.com/s/1XLP7kl3RuadT2y12VmOHeQ 提取码:6mlj
有什么不明白的可随时评论,我看到就会回复哦~
对你若有用,“好文要顶”NA~
C# 将List转成树的两种方式(递归、循环)
标签:ati htm stat tps parentId code temp 准备 div
原文地址:https://www.cnblogs.com/pukua/p/13150689.html
评论