I have a collection of custom node that has a parent child relation. Each node can be a composite type (that has other child in it) or a simple type (leaf level node)
I want to write a function that will be give me list of all dead nodes. For example here is the node collection
Based on the above case, p2, p3, p8, p9, p10, p6, c1 are dead nodes (since down their hierarchy they don't have any simple node in them)
I need a function as
private List<NodeEntity> GetDeadNodes(List<NodeEntity> originalList)
Here is the function for has the original list
private List<NodeEntity> GetOriginalList()
{
var list = new List<NodeEntity>()
{
new NodeEntity() {Code = "P1", ParentCode = "001", Type = NodeType.Composite},
new NodeEntity() {Code = "C1", ParentCode = "001", Type = NodeType.Composite},
new NodeEntity() {Code = "P2", ParentCode = "P1", Type = NodeType.Composite},
new NodeEntity() {Code = "P3", ParentCode = "P2", Type = NodeType.Composite},
new NodeEntity() {Code = "P8", ParentCode = "P3", Type = NodeType.Composite},
new NodeEntity() {Code = "P9", ParentCode = "P3", Type = NodeType.Composite},
new NodeEntity() {Code = "P4", ParentCode = "P1", Type = NodeType.Composite},
new NodeEntity() {Code = "L3", ParentCode = "P1", Type = NodeType.Simple},
new NodeEntity() {Code = "P6", ParentCode = "P1", Type = NodeType.Composite},
new NodeEntity() {Code = "P10", ParentCode = "P4", Type = NodeType.Composite},
new NodeEntity() {Code = "L2", ParentCode = "P4", Type = NodeType.Simple},
new NodeEntity() {Code = "P5", ParentCode = "P4", Type = NodeType.Composite},
new NodeEntity() {Code = "L1", ParentCode = "P5", Type = NodeType.Simple}
};
return list;
}
You can try something like that.
private List<NodeEntity> GetDeadNodes(List<NodeEntity> originalList)
{
var rest = originalList.ToList();
// Remove simple nodes and their ascendants.
// The rest will be dead nodes.
var simpleNodes = originalList.Where(n => n.Type == NodeType.Simple);
foreach (var simpleNode in simpleNodes)
{
rest.Remove(simpleNode);
RemoveAscendants(rest, simpleNode);
}
return rest;
}
private void RemoveAscendants(List<NodeEntity> rest, NodeEntity node)
{
var parent = rest.SingleOrDefault(n => n.Code == node.ParentCode);
// We have reached the root node.
if (parent == null)
{
return;
}
rest.Remove(parent);
RemoveAscendants(rest, parent);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments