using System;
using System.Collections;
using System.Collections.Generic;
namespace Ewide.Core
{
///
/// 树基类
///
public interface ITreeNode
{
///
/// 获取节点id
///
///
string GetId();
///
/// 获取节点父id
///
///
string GetPid();
///
/// 设置Children
///
///
void SetChildren(IList children);
}
public class TreeBuildSetting
{
public bool AddEmptyChildren { get; set; } = true;
}
///
/// 递归工具类,用于遍历有父子关系的节点,例如菜单树,字典树等等
///
///
public class TreeBuildUtil where T : ITreeNode
{
TreeBuildSetting _setting;
public TreeBuildUtil(TreeBuildSetting setting = null)
{
_setting = setting ?? new TreeBuildSetting();
}
///
/// 顶级节点的父节点Id(默认0)
///
private readonly List _rootParentIds = new List { string.Empty, Guid.Empty.ToString() };
///
/// 构造树节点
///
///
///
public List DoTreeBuild(List nodes)
{
nodes.ForEach(u => BuildChildNodes(nodes, u, new List()));
var results = new List();
nodes.ForEach(u =>
{
if (_rootParentIds.Contains(u.GetPid()))
results.Add(u);
});
// 在未获取到根节点的情况下, 直接将最上级作为根节点
if (results.Count < 1)
{
var ids = new List();
nodes.ForEach(u =>
{
ids.Add(u.GetId());
});
nodes.ForEach(u =>
{
if (!ids.Contains(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);
if (childNodeLists.Count > 0 || _setting.AddEmptyChildren)
{
node.SetChildren(childNodeLists);
}
}
}
}