C# LINQ recursive query to show parent child relation

T.Zacks 3,996 Reputation points
2021-05-03T18:46:45.42+00:00

I have a example which showing parent child relation in hierarchical way but one minor issue facing. i have a property called hierarchy which will show 0000+ID for parent row which has parent id is zero and for all child rows it will have Parent hierarchy plus child id. for this issue i am not being able to do it. so please have look at my code and tell me how to fix this area.

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 2", ParentId = 1 },
        new Comment() { Id = 3, Text = "Item 3", ParentId = 2 },
        new Comment() { Id = 4, Text = "Item 1.1", ParentId = 1 },
        new Comment() { Id = 5, Text = "Item 3.1", ParentId = 3 },
        new Comment() { Id = 6, Text = "Item 1.1.1", ParentId = 4 },
        new Comment() { Id = 7, Text = "Item 2.1", 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();

    HieararchyWalk(hierarchy);
}

        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 = "0000" +comments.Where(a => a.Id == parentId).FirstOrDefault().Id + ".0000" + c.Id,
                        Children = GetChildren(comments, c.Id)
                    })
                    .ToList();
        }

public void HieararchyWalk(List<Comment> hierarchy)
{
    if (hierarchy != null)
    {
        foreach (var item in hierarchy)
        {
            //Console.WriteLine(string.Format("{0} {1}", item.Id, item.Text));
            textBox1.Text += item.Id + " " + item.Text+ "Hierarchy-"+ item.hierarchy + System.Environment.NewLine;
            HieararchyWalk(item.Children);
        }
    }
}

public class Comment
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string hierarchy { get; set; }
    public string Text { get; set; }
    public List<Comment> Children { get; set; }
}

When calling HieararchyWalk() then hierarchy property not showing value right way.

hierarchy not showing in chain wise. parent hierarchy -> child hierarchy -> again child hierarchy this way it should be shown.

Parent hierarchy is not getting carry forward for nested child....where the problem lies ? please help me to fix this problem. Thanks

Developer technologies C#
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-05-04T02:09:31.653+00:00

    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);  
                        }  
                    }  
                }  
            }  
    

    93447-1.png

    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;  
            }  
    

    97151-3.png


    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.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Sangam Dhani 1 Reputation point
    2022-10-18T09:38:07.373+00:00

    Hello,
    I got the same solution in .Net Core WEB API. Please check the link: https://youtu.be/SzyReVDLB2M

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.