using iWareCommon.Common.Entity; using System.Collections.Generic; namespace iWareCommon.Utils { /// /// 树形结构中使用的方法 /// public class TreeHelper where T:class, ITreeEntity { /// /// 将平面的T拼装成类型记录列表转换为以id为键,子记录列表为值的字典 /// /// 平面的T类型的记录 /// 以id为键,子记录列表为值的字典 public static Dictionary> GetChildrenDictionary(List ts) { //以id为键,子记录列表为值的字典 var childrenDictionary = new Dictionary>(); foreach (var t in ts) { if (!childrenDictionary.ContainsKey(t.ParentId)) { childrenDictionary.Add(t.ParentId, new List { t }); } else { childrenDictionary[t.ParentId].Add(t); } } foreach (var t in ts) { if (childrenDictionary.ContainsKey(t.Id)) { t.Children = childrenDictionary[t.Id]; } } return childrenDictionary; } /// /// 判断是否是主键为childId的T记录是否为主键为parentId的T记录的子记录或其本身 /// /// 主键为parentId的T记录Id /// 主键为childId的T记录Id/param> /// 以T记录id为键,T子记录为值的T列表 /// 主键为childId的T记录是否为主键为parentId的T记录的子记录或其本身 public static bool IsChildOrEq(int childId, int parentId, Dictionary> childrenDictionary) { if (parentId == childId) { return true; } if (!childrenDictionary.ContainsKey(parentId)) { return false; } foreach (var child in childrenDictionary[parentId]) { if (IsChildOrEq(child.Id, childId, childrenDictionary)) { return true; } } return false; } } }