I have a List of user-defined objects that have an ID and a ParentID. The list looks something like this.
ParentID ID
123 345
123 456
456 567
456 678
678 789
I need a LINQ statement to find the top level parent; that is, all of the objects where the ParentID does not exist in as an ID (in this example, only 123).
Here is what I have so far and it is returning 567,678,789.
parentList = baseList.Where(b => !baseList.Select(o => o.ParentID).Distinct().Contains(b.ID)).ToList();
Your current query is trying to find all the items where their ID doesn't correspond to any other item's parent ID--in other words, you're finding all childless nodes.
What it sounds like you want is all the parentless nodes--those whose parent ID doesn't match any other item's ID.
var ids = new HashSet<int>(baseList.Select(o => o.ID));
var itemsWithNoParent = baseList.Where(o => !ids.Contains(o.ParentID))
.ToList();
I'm using a HashSet<>
to ensure reasonable .Contains()
performance on large collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With