I have an observable collection whiich I want to remove a specific instance item from.
e.g.
data[1].ChildElements[0].ChildElements[1].ChildElements.RemoveAt(1);
This works fine, however, as this is relating to deleting child elements from a treeview, I want to dynamically create the above statement dependant on what level of the treeview is clicked. So i could want:
data[0].ChildElements[1].ChildElements.RemoveAt(0);
or
data[1].ChildElements.RemoveAt(0);
I know the id's of the parent items which I have stored away in a list, e.g.
0
1
0
or 1,0
My question is how do I go about creating the above statement when I dont know exactly how many items there are going to be in the list collection?
Thanks.
Sometimes old school does it best.
static void RemoveByPath(YourClass currentNode, int[] path)
{
for (int i = 0; i < path.Length - 1; i++)
{
currentNode = currentNode.ChildElements[path[i]];
}
currentNode.ChildElements.RemoveAt(path[path.Length-1]));
}
in case you don't have a "Root" YourClass
instance (I suspect you do but just in case) add:-
static void RemoveByPath(IList<YourClass> data, int[] path)
{
if (path.Length > 1)
{
RemoveByPath(data[path[0]], path.Skip(1).ToArray());
}
else
{
data.RemoveAt(path[0]);
}
}
then if you do want something clever you might turn these into extension methods.
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