Adding multiple children at multiple levels with a loop and "clean" code
I have a C# Class that can contain multiple children at multiple levels.
Adding children manually would look something like this:
CustomClass MyClass = new CustomClass(“something”, new List<CustomClass>());
//Level 1
MyClass.Children.Add(“something”, new List<CustomClass>());
//Level 2
MyClass.Children[0].Children.Add(“something”, new List<CustomClass>());
//Level 3
MyClass.Children[0].Children[0].Children.Add(“something”, new List<CustomClass>());
How would I do this with a clean loop instead? Doing it like this, doesn’t feel “right”:
for (var i = 0; i < 50; i++) {
//Level 1
if (i == 0)
MyClass.Children.Add(“something”, new List<CustomClass>());
//Level 2
if (i == 1)
MyClass.Children[0].Children.Add(“something”, new List<CustomClass>());
//Level 3
if (i == 2)
MyClass.Children[0].Children[0].Children.Add(“something”, new List<CustomClass>());
// and so on up to 50 le开发者_如何学JAVAvels in this case ...
}
IMPORTANT UPDATE: At every level I need to check if the value already exists, if it doesn't, I add it.
Thank you for listening!
I'm a beginner so please be gentle.
You could do it recursively:
void FillChildren(CustomClass lastChild, int levels)
{
if(levels > 0)
{
CustomClass child = new CustomClass(“something”, new List<CustomClass>());
FillChildren(child, levels-1);
lastChild.Children.Add(“something”, child);
}
}
Which you would call like so:
CustomClass MyClass = new CustomClass(“something”, new List<CustomClass>());
FillChildren(MyClass, 50);
精彩评论