using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BPA.SAAS.Manage.Comm.Util
{
///
/// 树基类
///
public interface ITreeNode
{
///
/// 获取节点id
///
///
string GetId();
///
/// 获取节点父id
///
///
string GetPid();
///
/// 设置Children
///
///
void SetChildren(IList children);
}
///
/// 递归工具类,用于遍历有父子关系的节点,例如菜单树,字典树等等
///
///
public class TreeBuildUtil where T : ITreeNode
{
///
/// 顶级节点的父节点Id(默认00000000-0000-0000-0000-000000000000)
///
private readonly string _rootParentId = "0";
///
/// 构造树节点
///
///
///
public List Build(List nodes)
{
nodes.ForEach(u => BuildChildNodes(nodes, u, new List()));
var result = new List();
nodes.ForEach(u =>
{
if (_rootParentId == u.GetPid())
result.Add(u);
});
return result;
}
///
/// 构造子节点集合
///
///
///
///
private void BuildChildNodes(List totalNodes, T node, List childNodeList)
{
var nodeSubList = new List();
totalNodes.ForEach(u =>
{
if (u.GetPid().Equals(node.GetId()))
nodeSubList.Add(u);
});
nodeSubList.ForEach(u => BuildChildNodes(totalNodes, u, new List()));
childNodeList.AddRange(nodeSubList);
node.SetChildren(childNodeList);
}
}
}