Reputation: 5001
Given a common parent/child table:
Table A
Column Id int
Column Parent_Id int
Column Description text
I would like to only get the nodes that does not have any child nodes.
1,null,"PARENT A"
2,null,"PARENT B",
3,null,"PARENT C",
100,1,"CHILD A1",
101,1,"CHILD A2",
102,2,"CHILD B1"
So for my resultset I would like to only get:
Parent C (as it does not have any child elements), and child A1, B2, B1.
Upvotes: 0
Views: 426
Reputation: 10222
You might wanna prefer Any() method instead of Count() == 0. See Which method performs better: .Any() vs .Count() > 0?
var itemsWithoutChildren = nodes.Where(item=>!nodes.Any(innerItem=>innerItem.Parent_Id==item.Id))
Upvotes: 1
Reputation: 437654
You don't say what exactly you are querying with LINQ, but the general idea is
var leafNodes = nodes.Where(n => nodes.Count(n1 => n1.Parent_Id == n.Id) == 0);
Upvotes: 1