I have : a list of items. Each item in this list can have the own list with the same structure. The depth of this list can be conditionally unlimited.
I need : Having The List of items IDs remove any items wherever it was without waste of plenty of time I know how to implement searching on graph algorithm, I need a solution which will allow me to bypass a simple enumeration.
Item Structure looks like this, but its not final and i can change it if needed
public class NavigationPath
{
public int Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public List<NavigationPath> Childs { get; set; }
}
CodePudding user response:
Following method is the fastest for your given data structure. Add it to your class NavigationPath
public void Remove(int id)
{
for (int i = 0; i < Childs.Count; i )
{
if (Childs[i].Id == id)
{
Childs.RemoveAt(i);
i--;
}
else
{
Childs[i].Remove(id);
}
}
}
If speed of removal is that important then another idea is to use LinkedList<>
instead of List<>
, hence
public LinkedList<NavigationPath> Childs { get; set; }
And then code for removal would be
public void Remove(int id)
{
var first = Childs.First;
while (first != null)
{
var next = first.Next;
if (first.Value.Id == id)
{
first.List.Remove(first);
}
else
{
first.Value.Remove(id);
}
first = next;
}
}