I have a list of nested comments that essentially form a tree.
//Non-Relevant properties (Like Body, Creator etc) excluded
internal class Comment
{
public int ID { get; set; }
public int ItemID { get; set; }
public int ParentItemID { get; set; }
public List<Comment> ChildComments { get; set; }
}
First, I get a list of Posts from a database, then I get all Comments where ItemID == Posts[all].id
I want to loop through a flat List and create a nested, or tree List.
It goes like this:
If the ParentItemID == 0, then we have a top level comment. If ParentItemID > 0 we need to match ParentItemID to a Comment ID, and add the child Comment to the Parent Comments List.
Where I’m stuck is, I’ve only used recursion in the past to navigate files and folders. This doesn’t allow me to instantiate a collection and hold on to it through subsequent recursions.
It also seems silly to instantiate the list outside the recursion, and then loop through all items each time I want to add an item.
I’m sure there is a good solid pattern for doing this, I just can’t find it.
You can just loop through all comments and get the child comments for each:
Another alternative that would perform better (if that is needed) would be to group the comments on the
ParentItemIDand create aDictionary<int, List<Comment>>from that, then just loop through the comments like above and get the lists from the dictionary.