zoukankan      html  css  js  c++  java
  • C#生成树形结构泛型类

    C#生成树形结构泛型类,使用方法: ToTree<ShowMessageUpdatesTableTreeViewModel>.ToDo(models) 

    public class ToTree<T> where T : IToTreeModel
    {
        public static List<T> ToDo(List<T> models)
        {
            var dtoMap = new Dictionary<int, T>();
            foreach (var item in models)
            {
                dtoMap.Add(item.Id, item);
            }
            List<T> result = new List<T>();
            foreach (var item in dtoMap.Values)
            {
                if (item.ParentId == 0)
                {
                    result.Add(item);
                }
                else
                {
                    if (dtoMap.ContainsKey(item.ParentId))
                    {
                        dtoMap[item.ParentId].AddChilrden(item);
                    }
                }
            }
            return result;
        }
    }

    实体类必须实现接口:

    public interface IToTreeModel
    {
        int Id { get; set; }
        int ParentId { get; set; }
        List<IToTreeModel> children { get; set; }
        void AddChilrden(IToTreeModel node);
    }

     实体类实例:

        public class ShowMessageUpdatesViewModel: IToTreeModel
        {
            public int Id { get; set; }
            public int ParentId { get; set; }
            public string Name { get; set; }
            public List<IToTreeModel> children { get; set; }
            public void AddChilrden(IToTreeModel node)
            {
                if (children == null)
                    children = new List<IToTreeModel>();
                this.children.Add(node);
            }
        }
  • 相关阅读:
    多校第四场
    codechef 两题
    Topcoder 多校T-shirt场
    状态压缩DP
    LUCAS 定理
    HDU 1104 Remainder
    HDU4542 小明系列故事——未知剩余系
    Codeforces Round #256 (Div. 2)
    Codeforces Round #FF (Div. 2)
    2016年川师大软件工程学生博客打分
  • 原文地址:https://www.cnblogs.com/ANPY/p/10089819.html
Copyright © 2011-2022 走看看