schangxiang@126.com
2025-09-23 1ec17ce75f4e4324e9756a91c74f3f52928c9351
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using iWareCommon.Common.Entity;
using System.Collections.Generic;
 
namespace iWareCommon.Utils
{
    /// <summary>
    /// 树形结构中使用的方法
    /// </summary>
    public class TreeHelper<T> where T:class, ITreeEntity<T>
    {
        /// <summary>
        /// 将平面的T拼装成类型记录列表转换为以id为键,子记录列表为值的字典
        /// </summary>
        /// <param name="planContents">平面的T类型的记录</param>
        /// <returns>以id为键,子记录列表为值的字典</returns>
        public static Dictionary<int, List<T>> GetChildrenDictionary(List<T> ts) 
        {
            //以id为键,子记录列表为值的字典
            var childrenDictionary = new Dictionary<int, List<T>>();
 
            foreach (var t in ts)
            {
               
                if (!childrenDictionary.ContainsKey(t.ParentId))
                {
                    childrenDictionary.Add(t.ParentId, new List<T> { t });
                }
                else
                {
                    childrenDictionary[t.ParentId].Add(t);
                }
            }
 
            foreach (var t in ts)
            {
                if (childrenDictionary.ContainsKey(t.Id))
                {
                    t.Children = childrenDictionary[t.Id];
                }
            }
 
            return childrenDictionary;
           
        }
 
        /// <summary>
        /// 判断是否是主键为childId的T记录是否为主键为parentId的T记录的子记录或其本身
        /// </summary>
        /// <param name="parentId">主键为parentId的T记录Id</param>
        /// <param name="childId">主键为childId的T记录Id/param>
        /// <param name="childrenDictionary">以T记录id为键,T子记录为值的T列表</param>
        /// <returns>主键为childId的T记录是否为主键为parentId的T记录的子记录或其本身</returns>
        public static bool IsChildOrEq(int childId, int parentId, Dictionary<int, List<T>> 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;
        }
 
 
    }
}