I have a class Item that looks as follows:
public class Item
{
public string Name { get; set; }
public int Value { get; set; }
public List<Item> SubItems { get; set; }
}
Items can be nested over n levels, meaning that any item can contain a list of items of which each contains a list of items ...
I want to write a method that accepts an instance of item as an argument and returns the sum of value of all nested items.
My current recursive approach looks as follows:
public int GetSumOfValue(Item item)
{
int sum = item.Value;
if (item.SubItems == null)
{
return sum;
}
foreach (var subItem in item.SubItems)
{
sum += GetSumOfValue(subItem);
}
return sum;
}
While this works, I read that an iterative approach using a loop would be faster in most cases.
(Please note that I abstracted and shortened this method for the sake of brevity. This is not production code.)
I have a hard time figuring out how to turn my recursive approach into an iterative one since there are nested classes.
Any hints are appreciated. Thanks.