1. 程式人生 > 實用技巧 >List轉Tree(List轉樹狀結構)

List轉Tree(List轉樹狀結構)

網上發現沒有簡潔明晰的Listto Tree程式碼,眾所周知宇宙第一IDE的原因對寫了一個C#版本的,後續有機會再寫一個java的吧。需要java的可以看一下思路

  1 using System;
  2 using System.Collections.Generic;
  3 using Newtonsoft.Json;
  4 using System.Linq;
  5 
  6 namespace ListToTree
  7 {
  8     class Program
  9     {
 10         static void Main(string[] args)
11 { 12 List<Tree> tree = ListToTree(CreteListNameData(), 0); 13 string res = JsonConvert.SerializeObject(tree); 14 15 16 Console.WriteLine(res); 17 Console.ReadLine(); 18 19 20 } 21 private static List<Tree> ListToTree(List<Name> list, int
pid) 22 { 23 24 if (list == null || list.Count == 0) 25 { 26 return null; 27 } 28 else 29 { 30 List<Tree> treeList = new List<Tree>(); 31 GetTreeListByPid(list, pid, treeList);
32 return treeList; 33 } 34 35 36 } 37 private static List<Tree> GetTreeListByPid(List<Name> list, int pid, List<Tree> treeList) 38 { 39 40 List<Name> listPidName = list.Where(a => a.pid == pid).ToList(); 41 //list.RemoveAll(a => a.pid == pid); 42 List<Tree> treeRes = listPidName.Select(a => new Tree() { id = a.id, name = a.name, pid = a.pid }).ToList(); 43 if (treeList == null || treeList.Count == 0) 44 { 45 treeList.AddRange(treeRes); 46 } 47 48 foreach (var tree in treeRes) 49 { 50 tree.children = GetTreeListByPid(list, tree.id, treeList); 51 } 52 return treeRes; 53 54 } 55 private static List<Name> CreteListNameData() 56 { 57 List<Name> list = new List<Name>() 58 { 59 new Name(1,0,"北京"), 60 new Name(2,0,"河北"), 61 62 new Name(3,1,"密雲"), 63 new Name(4,1,"海淀"), 64 65 new Name(5,2,"興隆"), 66 new Name(6,2,"邢臺"), 67 68 new Name(7,3,"密雲鎮1"), 69 new Name(8,3,"密雲鎮2"), 70 new Name(9,4,"海淀鎮1"), 71 new Name(10,4,"海淀鎮2"), 72 73 new Name(11,5,"興隆鎮1"), 74 new Name(12,5,"興隆鎮2"), 75 new Name(13,6,"邢臺鎮1"), 76 new Name(14,6,"邢臺鎮2"), 77 }; 78 return list; 79 } 80 81 82 } 83 public class Name 84 { 85 public int id { set; get; } 86 public int pid { set; get; } 87 88 public string name { set; get; } 89 public Name(int id, int pid, string name) 90 { 91 this.id = id; 92 this.pid = pid; 93 this.name = name; 94 } 95 96 } 97 public class Tree 98 { 99 public int id { set; get; } 100 public int pid { set; get; } 101 102 public string name { set; get; } 103 public List<Tree> children { set; get; } = new List<Tree>(); 104 } 105 }