I have a list that contains data row objects which have two attributes, an Id and a prentId. An example would like this:
id ParentId
130 -1
131 130
132 131
133 131
134 132
135 131
136 132
137 136
138 136
139 136
143 136
If the list would be seen from an hierarchical point of view it would look like this:
130
131
132
134
136
137
138
139
143
133
135
What I would like to do is to create an algorithm that removes all the elements and sub elements which parents are matching a specific ID.
For example, if the chosen ID would be 132 then the elements with id 132, 134, 136, 137, 138, 139, 143 should be removed.
What I have tried until now goes like this
Private Function RemoveRecursive(ByRef values As List(Of DataRow), value As String) As List(Of DataRow)
For index As Integer = values.Count - 1 To 0 Step -1
If Not IsDBNull(values(index)("parent")) AndAlso values(index)("parent") = value Then
values.RemoveAt(index)
Return RemoveRecursive(values, value)
value = values(index)("id")
End If
Next
Return values
End Function
My attempt to solve you problem (c#):
private static void RemoveRecursive(List<DataRow> values, string valueToRemove) {
DataRow itemToRemove = values.Find(dr => (string)dr["id"] == valueToRemove);
values.Remove(itemToRemove);
IEnumerable<string> children = values.Where(dr => (string)dr["ParentId"] == valueToRemove).Select(dr => (string)dr["id"]);
foreach (string child in children)
RemoveRecursive(values, child);
}
You can invoke this method in this way:
RemoveRecursive(values, "131");
You can also add some null checkings.