I'm trying to build a structure like this :
- Parent 1
- Child 1
- Super child 1
- Child 2
- Super Child 2
- Super super Child 2
- Super Child 2
- Child 1
I don't know how many branches there will be.
I need to build my structure with an array of paths like this :
- Parent1/Child1/SuperChild1
- Parent1/Child2/SuperChild2/SupersuperChild2
I made a Model as following :
public class Person
{
public string Name { get; set; }
public string FullPath { get; set; }
public List<Person> Children { get; set; }
}
I split every paths to an array and then I interate inside with foreach :
string[] list =
{
"Parent1/Child1/SuperChild1/SupersuperChild1",
"Parent1/Child1/SuperChild1/SupersuperChild2",
"Parent2/Child2/SuperChild2/SupersuperChild3",
"Parent2/Child3/SuperChild3/SupersuperChild4",
"Parent2/Child3/SuperChild3/SupersuperChild5"
};
var branches = new List<Person>();
foreach (var tag in list)
{
var tagSlash = tag.Replace("[", "").Replace("]", "/").Split('/');
Person parent = null;
foreach (var step in tagSlash)
{
Person branch = null;
if (parent == null && branches.Find(b => b.Name.Equals(step)) == null)
{
branch = new Person
{
Name = step,
FullPath = tagSlash.Last().Equals(step) ? tag : null,
Children = new List<Person>()
};
branches.Add(branch);
}
else if (parent == null && branches.Find(b => b.Name.Equals(step)) != null)
{
branch = branches.Find(b => b.Name.Equals(step));
}
else if (parent.Children.Find(c => c.Name.Equals(step)) != null)
{
branch = parent.Children.Find(c => c.Name.Equals(step));
}
else
{
var ancestor =
branch = new Person
{
Name = step,
FullPath = tagSlash.Last().Equals(step) ? tag : null,
Children = new List<Person>()
};
}
parent = branch;
}
}
The previous code isn't finished because I'm stuck.
Do you have an idea on how to build that structure ?
Thank you.