using System.Collections;
using System.Collections.Generic;
namespace Magic.Core;
///
/// 树基类
///
public interface ITreeNode
{
///
/// 获取节点id
///
///
long GetId();
///
/// 获取节点父id
///
///
long GetPid();
///
/// 设置Children
///
///
void SetChildren(IList children);
}
///
/// 递归工具类,用于遍历有父子关系的节点,例如菜单树,字典树等等
///
///
public class TreeBuildUtil where T : ITreeNode
{
///
/// 顶级节点的父节点Id(默认0)
///
private readonly long _rootParentId = 0L;
///
/// 构造树节点
///
///
///
public List DoTreeBuild(List nodes)
{
nodes.ForEach(u => BuildChildNodes(nodes, u, new List()));
var results = new List();
nodes.ForEach(u =>
{
if (_rootParentId == u.GetPid())
results.Add(u);
});
return results;
}
///
/// 构造子节点集合
///
///
///
///
private void BuildChildNodes(List totalNodes, T node, List childNodeLists)
{
var nodeSubLists = new List();
totalNodes.ForEach(u =>
{
if (u.GetPid().Equals(node.GetId()))
nodeSubLists.Add(u);
});
nodeSubLists.ForEach(u => BuildChildNodes(totalNodes, u, new List()));
childNodeLists.AddRange(nodeSubLists);
node.SetChildren(childNodeLists);
}
}