Search code examples
c#recursionparent

c# datatable recursive output


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


Solution

  • 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"));