0

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.

Kman
  • 4,809
  • 7
  • 38
  • 62

2 Answers2

1

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);
Jon
  • 428,835
  • 81
  • 738
  • 806
1

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))
Community
  • 1
  • 1
M. Mennan Kara
  • 10,072
  • 2
  • 35
  • 39