I have an in memory List<TreeNode>. Is it possible to to use linq to select all leaf nodes?
The SQL would look something like this:
SELECT
t1.Name
FROM
Tree t1
LEFT JOIN Tree t2
ON t1.UserId = t2.ParentId
WHERE
t2.UserId is null
The closest that I’ve got is (i still need to filter out the nulls):
var test = from t1 in list
join t2 in list
on t1.UserId equals t2.ParentId into g
from result in g.DefaultIfEmpty()
select new {
t1.Name
};
Which produces the correct sql (when testing in linqpad) without the where clause. I can’t access t2 where I select the anonymous object of if I try to filter results on where t2 == null. Do I need to create a copy of the list and join onto that?
EDIT: Okay, I’d misunderstood before. So you’re basically after items (
t1) in the list where there isn’t no elementt2such thatt1.UserId == t2.ParentId? In that case, I suggest you use:I suspect you want:
Note that I’m not using an anonymous type here as you’re only selecting a single value.
Another alternative would be: