Basically I look for recursive loop logic to handle the case. I have seen another thread where dbroux provided sample for getting selecetd items but that does not help me.
You can reuse the same idea as for the selected items, i.e write a recursive extension method returning all layer items and then filter with the criteria you need (selected is just a particular case).For removing the additional difficulty is that you need the parent item as well in order to be able to call parent.LayerItems.Remove(layerItemToRemove);So you can tweak the extension method to return an enumeration of pair <Parent, Child> (using .net Tuple but you might create your own class).
public static class LegendExtensions{
// Go recursively through the LayerItems and return a tuple <parent, child> for each child
public static IEnumerable<Tuple<LayerItemViewModel, LayerItemViewModel>> GetAllParentChild(this LayerItemViewModel layerItem)
{
return layerItem == null || layerItem.LayerItems == null ?
Enumerable.Empty<Tuple<LayerItemViewModel, LayerItemViewModel>>() :
layerItem.LayerItems.SelectMany(child => new[] { new Tuple<LayerItemViewModel, LayerItemViewModel>(layerItem, child) }.Concat(GetAllParentChild(child)));
}
}
Then you can use that extension method to delete the items you want with code like:
var toDeletes = LayerItem.GetAllParentChild().Where(pair => new[] {"Service Agreement Areas", "HTE Routes", ....}.Contains(pair.Item2.Label)).ToArray();
foreach (var pair in toDeletes)
pair.Item1.LayerItems.Remove(pair.Item2);