Populate a tree from Hierarchical data using 1 LINQ statement

Posted by Midhat on Stack Overflow See other posts from Stack Overflow or by Midhat
Published on 2010-05-03T18:52:33Z Indexed on 2010/05/03 18:58 UTC
Read the original article Hit count: 253

Filed under:

Hi. 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 SLOC using 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?

© Stack Overflow or respective owner

Related posts about LINQ