There is no problem with your Linq statement, but the Text property in the example does not seem to correspond to the actual structure.
I just modified its Text property, and then to make the demonstration clearer, I added it to the TreeView instead of the Textbox.
private void button1_Click(object sender, EventArgs e)
{
List<Comment> categories = new List<Comment>()
{
new Comment () { Id = 1, Text = "Item 1", ParentId = 0},
new Comment() { Id = 2, Text = "Item 1.1", ParentId = 1 },
new Comment() { Id = 3, Text = "Item 1.1.1", ParentId = 2 },
new Comment() { Id = 4, Text = "Item 1.2", ParentId = 1 },
new Comment() { Id = 5, Text = "Item 1.1.1.1", ParentId = 3 },
new Comment() { Id = 6, Text = "Item 1.2.1", ParentId = 4 },
new Comment() { Id = 7, Text = "Item 1.1.2", ParentId = 2 }
};
List<Comment> hierarchy = new List<Comment>();
hierarchy = categories
.Where(c => c.ParentId == 0)
.Select(c => new Comment()
{
Id = c.Id,
Text = c.Text,
ParentId = c.ParentId,
hierarchy = "0000" + c.Id,
Children = GetChildren(categories, c.Id)
})
.ToList();
TreeNode rootNode = treeView1.Nodes.Add("Root");
HieararchyWalk(hierarchy, rootNode);
}
public void HieararchyWalk(List<Comment> hierarchy, TreeNode treeNode)
{
if (hierarchy != null)
{
foreach (var item in hierarchy)
{
TreeNode newTreeNode = treeNode.Nodes.Add(item.Id+ " " + item.Text + " Hierarchy-" + item.hierarchy);
if (item.Children.Count != 0)
{
HieararchyWalk(item.Children, newTreeNode);
}
}
}
}
Did I understand what you mean correctly?
Update(5/17):
Please try the following code:
public List<Comment> GetChildren(List<Comment> comments, int parentId)
{
return comments
.Where(c => c.ParentId == parentId)
.Select(c => new Comment
{
Id = c.Id,
Text = c.Text,
ParentId = c.ParentId,
hierarchy = GetHiera(comments,c,parentId),
Children = GetChildren(comments, c.Id)
})
.ToList();
}
public string GetHiera(List<Comment> comments, Comment comment, int parentId)
{
string hierarchy = "0000"+ comment.Id+" ";
Comment parentComm = comments.Where(a => a.Id == parentId).FirstOrDefault();
if (parentComm.ParentId!=0)
{
hierarchy = GetHiera(comments, parentComm, parentComm.ParentId)+hierarchy;
}
else
{
hierarchy ="0000"+ parentId +" "+ hierarchy+" " ;
}
return hierarchy;
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.