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;      
        }
posted @ 2021-03-12 12:43  Blog老中医  阅读(103)  评论(0编辑  收藏  举报