调用ToTree函数
//list = 数据集
//把数据集转换到TreeModel中
List<TreeModel> treeList = new List<TreeModel>();
foreach (var item in list)
{
TreeModel node = new TreeModel
{
id = item.ProjectTreeCode,
text = item.ProjectTreeName,
value = item.ProjectTreeCode,
parentId = item.UpCode,
complete = Iscomplete(item)
};
treeList.Add(node);
}
//treeList 所有数据
//upCode 上级Code
var childrenList = treeList.ToTree(upCode);
ToTree函数
/// <summary>
/// 树形数据转化
/// </summary>
/// <param name="list">数据</param>
/// <returns></returns>
public static List<TreeModel> ToTree(this List<TreeModel> list,string parentId = "")
{
Dictionary<string, List<TreeModel>> childrenMap = new Dictionary<string, List<TreeModel>>();
Dictionary<string, TreeModel> parentMap = new Dictionary<string, TreeModel>();
List<TreeModel> res = new List<TreeModel>();
//首先按照
foreach (var node in list)
{
node.hasChildren = false;
node.complete = true;
// 注册子节点映射表
if (!childrenMap.ContainsKey(node.parentId))
{
childrenMap.Add(node.parentId, new List<TreeModel>());
}
else if (parentMap.ContainsKey(node.parentId))
{
parentMap[node.parentId].hasChildren = true;
}
childrenMap[node.parentId].Add(node);
// 注册父节点映射节点表
parentMap.Add(node.id, node);
// 查找自己的子节点
if (!childrenMap.ContainsKey(node.id))
{
childrenMap.Add(node.id, new List<TreeModel>());
}
else
{
node.hasChildren = true;
}
node.ChildNodes = childrenMap[node.id];
}
if (string.IsNullOrEmpty(parentId))
{
// 获取祖先数据列表
foreach (var item in childrenMap)
{
if (!parentMap.ContainsKey(item.Key))
{
res.AddRange(item.Value);
}
}
}
else {
if (childrenMap.ContainsKey(parentId))
{
return childrenMap[parentId];
}
else {
return new List<TreeModel>();
}
}
return res;
}
TreeModel实体
public class TreeModel
{
/// <summary>
/// 节点id
/// </summary>
public string id { get; set; }
/// <summary>
/// 节点显示数据
/// </summary>
public string text { get; set; }
/// <summary>
/// 节点提示
/// </summary>
public string title { get; set; }
/// <summary>
/// 节点数值
/// </summary>
public string value { get; set; }
/// <summary>
/// 是否有子节点
/// </summary>
public bool hasChildren { get; set; }
/// <summary>
/// 是否展开
/// </summary>
public bool isexpand { get; set; }
/// <summary>
/// 子节点是否已经加载完成了
/// </summary>
public bool complete { get; set; }
/// <summary>
/// 子节点列表数据
/// </summary>
public List<TreeModel> ChildNodes { get; set; }
/// <summary>
/// 父级节点ID
/// </summary>
public string parentId { get; set; }
}