Find ultimate parent of an entity using recursion in c#
I have an Entity which in turn refers to same table which is its parent.
Below is the table which describes it more better.
| ID | Source_ID |
+----+----------+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 4 |
Now, when I am at ID = 5, I need to fetch its ultimate parent, which is ID
= 1.
I tried writing a function which is as below:
<entity> ultimateparententity;
internal <entity> FetchParentComponentRecursive(<entity> entity)
{
if (component.ParentEntity!= null)
{
FetchParentComponentRecursive(entity.ParentEntity);
}
else
{
ultimateparententity = component;
return component;
}
return component;
}
I am using variable declared at class level to return the ultimate parent
which is not totally right. Any directions will be helpful.
No comments:
Post a Comment