Implement unlimited classification by iteration and implement hierarchical classification by generation
Speaking of the infinitus classification, I believe many people know what it is and have done it before. I also believe that the most widely used method is to implement recursion.
Recently, I also want to create a menu with unlimited classification, but I don't want to use recursion. So I need to implement it in other ways, that is, iteration.
First, I need to define an entity model. Here is an example of an infinite province/city:
Class Loaction {public int ID {get; set;} public int PID {get; set;} public string Name {get; set ;}// local Name public int Level {get; set;} // depth}
Then write the method. here we need to take advantage of the features of stack first-in-first-out:
public static List<Loaction> Soft(List<Loaction> data, int pid) { Stack task = new Stack(); task.Push(pid); List<Loaction> tree = new List<Loaction>(); int level = 0; while (task.Count > 0) { bool flag = false; for (int i = 0; i < data.Count; i++) { var l = data[i]; if (l.PID == pid) { pid = l.ID; task.Push(l.ID); l.Level = level; level++; tree.Add(l); data.Remove(l); i--; flag=true; } } if (!flag) { task.Pop(); if (task.Count > 0) { pid = Convert.ToInt32(task.Peek()); level--; } } } return tree; }
Finally, prepare the data-> call-> output:
Static void Main (string [] args) {var data = new List <Loaction> (); data. add (new Loaction () {ID = 1, PID = 0, Name = "Beijing"}); data. add (new Loaction () {ID = 2, PID = 0, Name = "Guangdong"}); data. add (new Loaction () {ID = 3, PID = 0, Name = "Shanghai"}); data. add (new Loaction () {ID = 4, PID = 0, Name = "Chongqing"}); data. add (new Loaction () {ID = 5, PID = 0, Name = "Heilongjiang"}); data. add (new Loaction () {ID = 6, PID = 1, Name = "Fengtai"}); data. add (new Loaction () {ID = 7, PID = 1, Name = "Haidian"}); data. add (new Loaction () {ID = 8, PID = 1, Name = "Shijingshan"}); data. add (new Loaction () {ID = 9, PID = 3, Name = "Shanghai"}); data. add (new Loaction () {ID = 10, PID = 2, Name = "Guangzhou"}); data. add (new Loaction () {ID = 11, PID = 5, Name = "Qiqihar"}); data. add (new Loaction () {ID = 12, PID = 2, Name = "Maoming"}); data. add (new Loaction () {ID = 13, PID = 2, Name = "Shenzhen"}); data. add (new Loaction () {ID = 14, PID = 5, Name = "Harbin"}); data. add (new Loaction () {ID = 15, PID = 4, Name = "Chongqing"}); data. add (new Loaction () {ID = 16, PID = 2, Name = "Dongguan"}); data. add (new Loaction () {ID = 17, PID = 2, Name = "Zhongshan"}); data. add (new Loaction () {ID = 18, PID = 16, Name = "Houjie Town"}); var tree = Soft (data, 0); foreach (var t in tree) {var sb = new StringBuilder (); for (int I = 0; I <t. level; I ++) {sb. append ("");} sb. append (t. name); Console. writeLine (sb. toString ();} Console. readKey ();}
Then the effect is as follows:
That's what it looks like ..... (END)