Removing from the Observable Collection

I have an observable collection in which I want to delete a specific instance element.

eg.

data[1].ChildElements[0].ChildElements[1].ChildElements.RemoveAt(1);

This works fine, however, since it involves deleting children from the tree, I want to dynamically create the above statement, depending on what level the tree clicks. Therefore, I might want:

data[0].ChildElements[1].ChildElements.RemoveAt(0);

or

data[1].ChildElements.RemoveAt(0);

I know the identifier of the parent elements that I saved in the list, for example

0 1 0 or 1,0

My question is, how can I create the above statement when I don’t know exactly how many elements will be in the list collection?

Thank.

+5
source share
3 answers

Sometimes the 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]));
  }

"Root" YourClass ( , , ) : -

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]);
    }
}

, - , .

+1

, Actual/Current node, ObservableCollection .

0

Something like that:

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);
        }
    }
0
source

All Articles