I have a self-binding table with id, CategoryName and ParentId. This is a typical scenario of a hierarchical table of categories that can be divided into categories that DB experts tell me is called an adjacency model.
I want to use Linq to SQL to query subcategories that are themselves not related to any other subcategories, that is, they are direct leaf nodes of any particular category or subcategory.
The simple part I got is that it just gets subcategories. Almost embarrassed to put the code here. But we really like the code.
IList<Categories> subcategories = context.Where( c => c.ParentId == 1).ToList();
But narrowing it down to categories without subcategories turns me on. Any help would be greatly appreciated.
Thanks for the help. Jeff
UPDATE ** It would seem that this works, but if someone can confirm that it is "correct", I would be grateful. So, if I want leaf nodes under a category with Id = 1, I would do the following:
Categories.Where( c => !c.Children.Any ( d => d.ParentId == c.Id)).Where( e => e.ParentId == 1)
"Children" is the Linq name giving an association of self-regulation.
source
share