我有一个包含以下内容的嵌套列表
public class Person
{
public Person(string name)
{
this.Name = name;
}
public string Name { get; set; }
public List<Person> Childs { get; set; }
}
该列表的用法如下:
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");
如何展平此树(将所有节点和子节点,以及子子节点放在列表中),例如,我希望使用level参数显示同一级别上的所有子节点和父节点。这意味着:
之前:
-Eric
-Tom
-John
-Bill
我想要的:
-Eric, Level1
-Tom, Level2
-John, Level2
-Bill, Level3
发布于 2019-03-06 17:28:08
递归方法的完美用例
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);
}
}
}
发布于 2020-01-27 17:06:58
在不改变原始模型的情况下展平一棵树的非常简短的代码:
static void Main(string[] args)
{
var flattedTree=new List<Person>();
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"));
Flatten(Persons, flattedTree);
//flattedTree variable is the flatted model of tree.
}
static void Flatten(List<Person> nodes, List<Person> flattedNodes)
{
foreach (var node in nodes)
{
flattedNodes.Add(node);
if (node.Childs?.Count > 0)
Flatten(node.Childs, flattedNodes);
}
}
https://stackoverflow.com/questions/55019486
复制相似问题