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 778163
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T19:43:15+00:00 2026-05-14T19:43:15+00:00

I have set up this programming exercise. using System; using System.Collections.Generic; using System.Linq; using

  • 0

I have set up this programming exercise.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{

    class DataObject {
       public int ID { get; set; }
       public int ParentID { get; set; }
       public string Data { get; set; }
       public  DataObject(int id, int pid, string data) { this.ID = id; this.ParentID = pid; this.Data = data; }
    }

    class TreeNode {
        public DataObject Data {get;set;}
        public List<DataObject> Children { get; set; }
    }


    class Program
    {

        static void Main(string[] args)
        {
            List<DataObject> data = new List<DataObject>();
            data.Add(new DataObject(1, 0, "Item 1"));
            data.Add(new DataObject(2, 0, "Item 2"));
            data.Add(new DataObject(21, 2, "Item 2.1"));
            data.Add(new DataObject(22, 2, "Item 2.2"));
            data.Add(new DataObject(221, 22, "Item 2.2.1"));
            data.Add(new DataObject(3, 0, "Item 3"));

        }
    }
}

The desired output is a List of 3 treenodes, having items 1, 2 and 3. Item 2 will have a list of 2 dataobjects as its children member and so on.

I have been trying to populate this tree (or rather a forest) using just 1 statement in LINQ. A simple group by gives me the desired data but the challenge is to organize it in TreeNode objects.

Can someone give a hint or an impossibility result for this?

  • 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-14T19:43:16+00:00Added an answer on May 14, 2026 at 7:43 pm

    LINQ does not do particularly well with recursive data structures, but you can get close.

    Since you probably want a tree of arbitrary depth, I’ll change your definition of Children and add a constructor a helper method that will do the recursion needed to make a tree-building LINQ statement possible.

    class TreeNode
    {
        public DataObject Data { get; set; }
        public List<TreeNode> Children { get; private set; }
    
        public TreeNode(DataObject data)
        {
            Data = data;
            Children = new List<TreeNode>();
        }
    
        //name chosen to match XElement method.  I would name this
        //SelfAndDescendants or change the behavior to match the name.
        public IEnumerable<TreeNode> DescendantsAndSelf()
        {
            return (new TreeNode[] { this }).Concat(from c in this.Children
                                                    from sc in c.DescendantsAndSelf()
                                                    select sc);
        }
    }
    

    Now we can define the following method:

    public static TreeNode BuildTree(IEnumerable<DataObject> items, int rootId)
    {
        var root = new TreeNode(new DataObject(rootId, int.MinValue, "Root"));
        return (from i in items
                let n = new TreeNode(i)
                group n by n.Data.ParentID into nodeGroup
                orderby nodeGroup.Key ascending
                select nodeGroup)
                .Aggregate(root, (parent, childGroup) =>
                {
                    parent.DescendantsAndSelf()
                          .First(n => n.Data.ID == childGroup.Key)
                          .Children.AddRange(childGroup);
                    return parent; 
                });
    }
    

    This method makes some assumptions, but should get you in the right direction.

    • None of the passed in elements are the root node of the tree and a root node will be created to be the return value.
    • The id of the parent node is always lower than the id of the node (this lets OrderBy + Aggregate be called to push the items into the tree)
    • Every item in the sequence passed to the method will belong to the root or one of the other items (otherwise an exception will be thrown by the .First() call).
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 431k
  • Answers 431k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I doubt very much whether this is possible. COM objects… May 15, 2026 at 2:20 pm
  • Editorial Team
    Editorial Team added an answer git fetch && git log ..origin/master is more precise. See… May 15, 2026 at 2:20 pm
  • Editorial Team
    Editorial Team added an answer Logical values take up fewer bytes than most numeric values,… May 15, 2026 at 2:20 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.