I have a data table that contains a one-to-many self referential relationship:
Plant
{
ID,
Name,
ParentID
}
I'm trying to create a linq query that will tell me the total number of descendants stemming from one Plant.
Example:
I have 5 plants:
One {ID = 1, Name = Pine, Parent = null};// This is the root
Two {ID = 2, Name = Evergreen, Parent = 1}
Three {ID = 3, Name = Winter Evergreen, Parent = 2}
Four {ID = 4, Name = Christmas Tree, Parent = 1}
Five {ID = 5, Name = Maple, Parent = null};// This is the root
When I call my LINQ query with an input of ID = 1
, I want it to return 3
, because there are 3 descendants of One
; Two, Three and Four. Five
is not a decedent of One.
The only way I can think about doing this involves nested recursive linq queries on the inner results. I have no idea how to do this and I feel as though there is an easier way.
I'm using C# 4.0 and LINQ if that matters.