I have a table called Groups. The structure of that table is :
GroupID 1-------
GroupName |
ParentID *-------
Now I want to find all the children and grand-children for a specific parent.
I have tried the below code. But it gives me children upto 2nd level only :
List<string> groups = new List<string>();
var parent = (from g in db.Groups
where g.GroupID == 1
select g).FirstOrDefault();
var Children = (from x in db.Groups
where x.ParentID == parent.GroupID
select x);
groups.AddRange(Children.Select(x => x.GroupName));
foreach (Group children in Children)
{
var grandChildren = (from x in db.Groups
where x.ParentID == children.GroupID
select x.GroupName);
groups.AddRange(grandChildren);
}
StringBuilder builder = new StringBuilder();
foreach (string str in groups)
{
builder.Append(str.ToString()).AppendLine();
}
MessageBox.Show(builder.ToString());