• 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;      
            }
    
  • 相关阅读:
    Redux API之applyMiddleware
    Redux API之combineReducers
    Redux API之creatStore
    Redux API之Store
    React-Redux之API
    ES6之6种遍历对象属性的方法
    React库protypes属性
    js立即执行函数
    Collection与Map总结
    02-再探MySQL数据库
  • 原文地址:https://www.cnblogs.com/SuperDust/p/14523209.html
Copyright © 2020-2023  润新知