Deleting from an Observable collection
I have an observ开发者_如何学编程able 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.
I would use Recursive functions, which can give you Actual/Current node, and the you can find out bound ObservableCollection and remove from it.
Something like this:
private void RemoveSpecificInstance(IList<int> ids, ObservableCollection<SomeClass> currentCollection)
{
if (ids.Count == 0)
{
// The initial collection didn't have children
return;
}
else if (ids.Count == 1)
{
currentCollection.RemoveAt(ids.Single());
}
else
{
int index = ids.First();
RemoveSpecificInstance(ids.Skip(1).ToList(), currentCollection[index].ChildElements);
}
}
精彩评论