Got datatable with Id, parentId, description. It is a relationial table structure.
I want to be able to pass a parameter to a function which is the current selected Id of the item in in treeview. I want to have a datatable returned with all the related children rows, the top of the relationship is parentId is null… etc etc
I would like to do this LINQ
Any help welcomed.
enter code here var kids = ( from p in dt.AsEnumerable()
where p.Field<Int32?>( "ParentId" ) == parentId
select new
{
parent = p,
child = from c in dt.AsEnumerable()
where c.Field<Int32?>( "ParentId" ) == p.Field<Int32>( "Id" )
select new
{
child = c
}
} ).ToList();
Below is the data I am using and I cannot get it to work as expected. Maybe we are not talking about the same end result or I am missing something terrible.
Here is the code I have and when I pass a value of 57 for the parentId I get 2 rows back in children.
QuotationItemId=58 and 71
I would expect also to get the QuotationItemId 59, 60, 55 ,56, 61
var lookup = dt.AsEnumerable().ToLookup( p => p.Field<int?>( "ParentId" ) );
var children = lookup[parentId].ToList();

This is what you can do:
Now if you want the root elements do this:
And if you want any children, given the
parentId, you do this:Simple, huh?
Here’s some code based on your edit.
I defined my list of items using an anonymous type:
And, using LINQPad, the lookup works like so:
You should note that it doesn’t recurse all the way down.
If you want to recurse all the way, then you need to define a recursive function. Try this:
And that gives you:
Which is what I think you’re expecting.