1

I have a class Node

 public class Node
    {
        public string Header { get; set; }
        public string Number { get; set; }
        public List<Node> Nodes { get; set; }
    }

The nested level is four levels. What I want to achieve is to find specified in function below string in any of nested lists. Here is a function:

public string getNumber(List<Node> currentList, string name)
    {
        string number = string.Empty;

        foreach (var item in currentList)
        {
            if (item.Header == name)
            {
                number = item.Number;
                return number;
            }
        }
        if (number == string.Empty)
        {
            foreach (var item in currentList)
            {
                number = getNumber(item.Nodes, name);
                return number;
            }
        }

        return null;
    }

It's iterating through first nested list from first item in list, but not for the rest items nested lists. Can anyone give me a hint where is my mistake?

Thanks.

zari
  • 67
  • 1
  • 10
  • I don't see the recursion here... maybe you ment to call `getNumber` again instead of `getNumberFromName` ? – kuskmen Jun 02 '17 at 14:56
  • my bad, should be getNumber instead, but anyway it doesn't work as it should. – zari Jun 02 '17 at 14:58

1 Answers1

3

You need to check if the recursive call found a number with a null check, otherwise you only check the sub list of the first item. Also you don't need to initialize number to empty or check it after the first foreach since you would have already returned if you found a match. And if you do find a match in the initial list you don't even need to set it to number, so you don't even need that variable until your second foreach.

public string getNumber(List<Node> currentList, string name)
{
    foreach (var item in currentList)
    {
        if (item.Header == name)
        {
            return item.Number;
        }
    }

   foreach (var item in currentList)
   {
       string number = getNumber(item.Nodes, name);
       if (number != null)
       {
           return number;
       }
   }

   return null;
}

Also you might want to think about the order you want to search stuff. Currently this will do a search in the following order

-1

--3

---5

---6

--4

---7

-2

--8

Where number of dashes represent the depth.

juharr
  • 31,741
  • 4
  • 58
  • 93