我有一个包含的嵌套列表
public class Person
{
public Person(string name)
{
this.Name = name;
}
public string Name { get; set; }
public List<Person> Childs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该列表可以像这样使用:
var Persons = new List<Person>();
Persons.Add(new Person("Eric"));
Persons[0].Childs = new List<Person>();
Persons[0].Childs.Add(new Person("Tom"));
Persons[0].Childs.Add(new Person("John"));
Persons[0].Childs[0].Childs = new List<Person>();
Persons[0].Childs[0].Childs.Add(new Person("Bill"));
Persons.Add(new Person("John");
Run Code Online (Sandbox Code Playgroud)
如何展平这棵树(将所有节点和子节点以及子子节点放入列表中),例如,我想在同一级别上使用“参数”级别显示所有子级和父级。这意味着:
之前:
-Eric
-Tom
-John
-Bill
Run Code Online (Sandbox Code Playgroud)
我想要的是:
-Eric, Level1
-Tom, Level2
-John, Level2
-Bill, Level3
Run Code Online (Sandbox Code Playgroud)
递归方法的完美用例
public static void DisplayPerson(List<Person> persons, int level = 0)
{
if (persons != null)
{
level++;
foreach (Person item in persons)
{
Console.WriteLine("-" + item.Name + ", Level" + level);
DisplayPerson(item.Childs, level);
}
}
}
Run Code Online (Sandbox Code Playgroud)
https://dotnetfiddle.net/2J9F5K