Link to home
Start Free TrialLog in
Avatar of mr-kenny
mr-kennyFlag for Switzerland

asked on

Build a Tree Object from a Table with Parent Child

Hallo,

I have a table in my DB with an Organisation that has each a key an a parent Id.
Further I have a C# Object OrganisationUnit that has a Property SubOrganisations.

Can someone provide me please a simple Algorithm to fill this Object so I have an Hiearchical Object? I guess I have to use rescursion but I'm stuck at the Moment.

Best regards
Patrik
SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mr-kenny

ASKER

Hi TommySzalapski

Thanks for the help. The OrgUnit Class contains: Id, ParentId, Name and List<OrgUnit> SubOrgUnits.
Could you please write some pseudo code of your solution?

Hi saragani,

Thank you, this worked.
I just have to add them to the parent. Thanks a lot

private void fillNodeWillChildren(OrganisationUnit  node)
{
   List<OrganisationUnit> children = getChildOrganisationUnitsByParentID(node.UniqueKey);

//Add them to Parent:
node.SubOrgUnits = children;


  foreach (vart child in children)
  {
     fillNodeWillChildren(child);
  }
}
Avatar of saragani
saragani

Hi, I just see that I wrote vart instead of var :-)
no Problem,

here my final solution:
thanks again,

        private OrgUnit NestTreeRecursive(List<OrgUnit> orgUnitList)
        {
            //Get Top of Tree
            OrgUnit topOrgUnit = (from o in orgUnitList where o.Level == 1 select o).Single();

            fillNodeWillChildren(topOrgUnit);

            return topOrgUnit;
        }

        private void fillNodeWillChildren(OrgUnit  node)
        {
            List<OrgUnit> children = getChildOrganisationUnitsByParentID(node.TreeId);

            node.SubOrgUnits = children;

            foreach (var child in children)
            {
                fillNodeWillChildren(child);
            }
        }

        private List<OrgUnit> getChildOrganisationUnitsByParentID(int ID)
        {
            List<OrgUnit> children = new List<OrgUnit>();

            children = (from o in OrgUnitsUnnested.Items where o.ParentId == ID orderby o.Name select o).ToList();

            return children;
        }

Open in new window