Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting from an Observable collection

Tags:

c#

silverlight

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.

like image 920
Simon Griffiths Avatar asked Nov 13 '22 18:11

Simon Griffiths


1 Answers

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.

like image 117
AnthonyWJones Avatar answered Dec 21 '22 10:12

AnthonyWJones