'C# Parent Child - Save To File ( I want to Save Parent Child Hyerarchy to the file)
i want to save Parent Child Hierarchy To the File
p.s Console Print Can Do , but i try with streamwriter to write to the text ,but cant
and wants that ID should be unique for the new person in the list
any advice?

Person person1 = new Person() { ID = 1, Name = "X..Parent" };
Person person2 = new Person() { ID = 2, Name = "Y...ChildOF..X" };
Person person3 = new Person() { ID = 3, Name = "Child of..Y" };
Person person4 = new Person() { ID = 4, Name = "Child of..Y" };
person1.Children.Add(person2);
person2.Children.Add(person3);
person2.Children.Add(person4);
PersonList people1 = new PersonList();
people1.Add(person1):
people1.Save(@"C:\People.txt");
Print(people1);
}
public static void Print(IEnumerable<Person> people, int level = 0)
{
foreach (var item in people)
{
Console.WriteLine($"{new string(' ', level * 2)}{item}");
Print(item.Children, level + 1);
}
}
}
class PersonList : List<Person>
{
new public void Add(Person item)
{
base.Add(item);
}
public void Save(string path)
{
}
}
class Person
{
public Person()
{
Children = new List<Person>();
}
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Person> Children { get; set; }
public override string ToString()
{
return $"ID: {ID}, Name: {Name}";
}
}
Solution 1:[1]
Here you go
public class PersonList {
List<Person> _people = new();
public List<Person> People {get {return _people;} }
public void Add(Person item) {
_people.Add(item);
}
public void Save(string path) {
using (var f = System.IO.File.Open(path, FileMode.Create))
using (var s = new StreamWriter(f)) {
int depth = 0;
foreach (Person item in _people) {
s.WriteLine(item.ToString());
Traverse(depth+1, s, item);
}
}
}
public void Traverse(int depth, StreamWriter s , Person p) {
foreach (var child in p.Children) {
s.Write(new string(' ', depth * 2));
s.WriteLine(child.ToString());
Traverse(depth+1, s, child);
}
}
}
plus
people1.Save(@"People.txt");
Print(people1.People);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
