• C# dynamic 树形结构


           static void Main(string[] args)
            {
                List<dynamic> arrayList = new List<dynamic>();
                arrayList.Add(new { id = "0", pid = "", title = "湖北省", children= new List<dynamic>() });
                arrayList.Add(new { id = "1", pid = "0", title = "武汉市", children = new List<dynamic>() });
                arrayList.Add(new { id = "2", pid = "0", title = "江夏区", children = new List<dynamic>() });
                arrayList.Add(new { id = "3", pid = "2", title = "未知", children = new List<dynamic>() });
          
                Console.WriteLine(JsonSerializer.Serialize(Totree(arrayList)));
      
            }
    
            public static List<dynamic> Totree(List<dynamic> oldList) 
            {
                Dictionary<string, dynamic> keyValuePairs = new Dictionary<string, dynamic>();
                foreach (var item in oldList)
                {
                    keyValuePairs.Add(item.id, item);
                }
                List<dynamic> newList = new List<dynamic>();
    
                foreach (var item in oldList)
                {
                    var parent = keyValuePairs.Where(t=>t.Key== item.pid).FirstOrDefault() ;
                    if (parent.Key!=null)
                    {
                        parent.Value.children.Add(item);
                    }
                    else
                    {
                        newList.Add(item);
                    }
                }
    
                return newList;      
            }
    
  • 相关阅读:
    Java中的各种锁总结2
    Java中锁的总结学习
    双亲委派模型
    mybatis中使用in查询问题
    ArrayList、LinkedList、Vector 区别,优缺点,实现原理
    java value注解总结
    linux-系统启动流程
    linux-文本编辑器
    linux-LVM 逻辑卷
    nodejs + access 应用
  • 原文地址:https://www.cnblogs.com/SuperDust/p/14523209.html
Copyright © 2020-2023  润新知