Linq - get elements that are top in hierarchy

1.1k views Asked by At

I have the following data:

enter image description here

I need to get the top elements in the tree data structure. All the rows where the AncestorId equals DescendantId are parents but I need first to get the top parents. For example:

2 and 34

Becuase element with ID 2 just exist once in the descendantid column, also for element with ID 34.

Then I have to get the children below ID 2 and ID 34 and so on so I can start building my tree structure.

This is how the table data should look line in a visual tree:

enter image description here

Right now I have the following Linq statement to get the parents nodes:

// get parent nodes
var parentNodes = data.Where(i => i.AncestorId == i.DescedantId ).ToList();

How can I get in a linq query the Top parents, and then how to get the children, etc?

1

There are 1 answers

6
Rufus L On BEST ANSWER

EDIT: To get the Top parents (i.e. they only appear once in Descendant Id), you can do the following

var parentNodes = data
    .Where(i => i.AncestorId == i.DescedantId &&
                (data.Count(d => d.DescedantId == i.DescedantId) == 1))
    .ToList();

And to get the children of a parent:

var allChildren = data.Except(parentNodes);
var someParent = parentNodes.First();
var someParentsChildren = 
    allChildren.Where(i => i.AncestorId == someParent.DescendantId)