Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 574853
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T13:52:33+00:00 2026-05-13T13:52:33+00:00

I’ll try to explain this the best I can. I’m having quite a bit

  • 0

I’ll try to explain this the best I can. I’m having quite a bit of difficulty trying to figure out this logic.

Basically, I have a collection that includes thousands of objects which are each made up of a Parent and a Child property.

So, roughly, this:


public class MyObject{
     public string Parent { get; set; }
     public string Child { get; set; }
}

What I’m trying to figure out is how to build this out into a plain TreeView control. I need to build the relationships but I can’t figure out how to because they can be mixed. I can probably explain this better with what the tree should look like:

So if I have the following items inside of my collection:


0. Parent: "A", Child: "B"
1. Parent: "B", Child: "C"
2. Parent: "B", Child: "D"

I would want my tree to look this like:


-A
--B
---C
-A
--B
---D
-B
--C
-B
--D

How can I do this in C#? I would need it to support up to N relationships as we have some branches I would expect to reach about 50 nodes deep.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T13:52:33+00:00Added an answer on May 13, 2026 at 1:52 pm

    UPDATE

    This problem actually turned out to be considerably more complex than I originally realized, given the requirement of repeating the entire tree for each path. I’ve simply deleted the old code as I don’t want to add any further confusion.

    I do want to keep it on record that using a recursive data structure makes this easier:

    public class MyRecursiveObject
    {
        public MyRecursiveObject Parent { get; set; }
        public string Name { get; set; }
        public List<MyRecursiveObject> Children { get; set; }
    }
    

    You’ll see very clearly why this is easier after reading the implementation code below:

    private void PopulateTree(IEnumerable<MyObject> items)
    {
        var groupedItems =
            from i in items
            group i by i.Parent into g
            select new { Name = g.Key, Children = g.Select(c => c.Child) };
        var lookup = groupedItems.ToDictionary(i => i.Name, i => i.Children);
        foreach (string parent in lookup.Keys)
        {
            if (lookup.ContainsKey(parent))
                AddToTree(lookup, Enumerable.Empty<string>(), parent);
        }
    }
    
    private void AddToTree(Dictionary<string, IEnumerable<string>> lookup,
        IEnumerable<string> path, string name)
    {
        IEnumerable<string> children;
        if (lookup.TryGetValue(name, out children))
        {
            IEnumerable<string> newPath = path.Concat(new string[] { name });
            foreach (string child in children)
                AddToTree(lookup, newPath, child);
        }
        else
        {
            TreeNode parentNode = null;
            foreach (string item in path)
                parentNode = AddTreeNode(parentNode, item);
            AddTreeNode(parentNode, name);
        }
    }
    
    private TreeNode AddTreeNode(TreeNode parent, string name)
    {
        TreeNode node = new TreeNode(name);
        if (parent != null)
            parent.Nodes.Add(node);
        else
            treeView1.Nodes.Add(node);
        return node;
    }
    

    First of all, I realized that the dictionary will contain keys for intermediate nodes as well as just the root nodes, so we don’t need two recursive calls in the recursive AddToTree method in order to get the “B” nodes as roots; the initial walk in the PopulateTree method already does it.

    What we do need to guard against is adding leaf nodes in the initial walk; using the data structure in question, these are detectable by checking whether or not there is a key in the parent dictionary. With a recursive data structure, this would be way easier: Just check for Parent == null. But, a recursive structure is not what we have, so the code above is what we have to use.

    The AddTreeNode is mostly a utility method, so we don’t have to keep repeating this null-checking logic later.

    The real ugliness is in the second, recursive AddToTree method. Because we are trying to create a unique copy of every single subtree, we can’t simply add a tree node and then recurse with that node as the parent. “A” only has one child here, “B”, but “B” has two children, “C” and “D”. There needs to be two copies of “A”, but there’s no way to know about that when “A” is originally passed to the AddToTree method.

    So what we actually have to do is not create any nodes until the final stage, and store a temporary path, for which I’ve chosen IEnumerable<string> because it’s immutable and therefore impossible to mess up. When there are more children to add, this method simply adds to the path and recurses; when there are no more children, it walks the entire saved path and adds a node for each.

    This is extremely inefficient because we are now creating a new enumerable on every invocation of AddToTree. For large numbers of nodes, it is likely to chew up a lot of memory. This works, but it would be a lot more efficient with a recursive data structure. Using the example structure at the top, you wouldn’t have to save the path at all or create the dictionary; when no children are left, simply walk up the path in a while loop using the Parent reference.

    Anyway, I guess that’s academic because this isn’t a recursive object, but I thought it was worth pointing out anyway as something to keep in mind for future designs. The code above will produce exactly the results you want, I’ve gone ahead and tested it on a real TreeView.


    UPDATE 2 – So it turns out that the version above is pretty brutal with respect to memory/stack, most likely a result of creating all those IEnumerable<string> instances. Although it’s not great design, we can remove that particular issue by changing to a mutable List<string>. The following snippet shows the differences:

    private void PopulateTree(IEnumerable<MyObject> items)
    {
        // Snip lookup-generation code - same as before ...
    
        List<string> path = new List<string>();
        foreach (string parent in lookup.Keys)
        {
            if (lookup.ContainsKey(parent))
                AddToTree(lookup, path, parent);
        }
    }
    
    private void AddToTree(Dictionary<string, IEnumerable<string>> lookup,
        IEnumerable<string> path, string name)
    {
        IEnumerable<string> children;
        if (lookup.TryGetValue(name, out children))
        {
            path.Add(name);
            foreach (string child in children)
                AddToTree(lookup, newPath, child);
            path.Remove(name);
        }
        // Snip "else" block - again, this part is the same as before ...
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Does anyone know how can I replace this 2 symbol below from the string
I have a jquery bug and I've been looking for hours now, I can't
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.