-2

I have a datatable that has the following structure:

id | parentid | name
1  | 0        | Parent
2  | 1        | Child
3  | 2        | child of child
4  | 1        | second child

I am stuck to output these as parent child(basically im trying to use open xml to output these as toc) can someone please help me to output them as parent child in a list or maybe dictionary...

Thanks

James
  • 177
  • 10
  • 19
  • have created a foreach loop where i get the rows and add to list...then have another list for ones that are children...but am lost of how to link them now – James Dec 13 '11 at 09:35
  • What output you expecting? example please... – Renatas M. Dec 13 '11 at 09:41
  • I don't think using a recursive function on a datatable would be smart. Just put the correct information in the datatable, save your recursive funcitons for the correct job, this isn't it – Security Hound Dec 14 '11 at 17:00

2 Answers2

1

Here is my suggestion for you. Create a data object (choose a better name and add some more properties if necessary) like this

public class DataNode
{
    public int Id { get; private set; }

    public string Name { get; set; }

    public List<DataNode> Children { get; private set; }

    public DataNode(int id, string name)
    {
        Id = id;
        Name = name;
        Children = new List<DataNode>();
    }
}

Create a list of those nodes like var dataNodeList = new List<DataNode>(); and add all element who don't have a parent directly to that list. Add each children to the Children list of the parent with parentid. To find a parent in your tree use this function:

public DataNode FindElementById(IEnumerable<DataNode> elementsToSearch, int id)
{
    foreach (var dataNode in elementsToSearch)
    {
        if (dataNode.Id == id)
        {
           return dataNode;
        }
        var found = FindElementById(dataNode.Children, id);
        if (found != null)
        {
           return found;
        }
     }
     return null;
 }
Bharath theorare
  • 524
  • 7
  • 27
Fischermaen
  • 12,238
  • 2
  • 39
  • 56
  • trying to follow this .... how do i do this part : Add each children to the Children list of the parent with parentid. – James Dec 14 '11 at 15:43
  • @user813741: Get the parent with the method `FindElementById` (provide the rootList and the parentId you are searching for). If you got a DataNode back (!= null) then you add the a new child node to the Children property of that parent with `foundParent.Children.Add(new DataNode(id, name));` – Fischermaen Dec 14 '11 at 16:57
0

Check out this solution. You can use it as follows:

var hierarchy =
    table.AsEnumerable().ToHierarchy(
        r => r.Field<int>("parentid") == 0,
        (parent, child) => parent.Field<int>("id") == child.Field<int>("parentid"));
Community
  • 1
  • 1
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758