I am implementing a tree think of it as a folder structure so I have a class that looks like:
public class Folder
{
//Various Props like Name etc.
public IList<Folder> Children{get;}
public Folder Parent {get;}
}
Now what I want is to be able to walk up and down the tree so given a root I can find a leaf, and given a leaf I can find the root node. So each child needs a parent. Now the question is what is the best way to add a new node to the tree. I have used two solutions in the past:
- Add an AddChild(Folder) method to Folder which handles adding the folder, and can set the parent. The problem with this is I now have to lock my Children collection so you can't bypass this method.
- Create my own Children collection which will be given a reference back to the instance, so it can handle setting the parent on the add. The problem with this I have to implement a new collection.
- Use a collection which has events when items are added or deleted.
I am curious what patterns people generally use, and then if anyone has any suggestions for my specific use case. I am using nHibernate to persist my tree to SQL server. I'd rather not implement a custom collection as it's a lot of code to get this to work for something which is a very small part of my application.