Home > Mobile >  list in recursive function is getting reset
list in recursive function is getting reset

Time:03-05

Inside a recursive function I append elements to a list (IEnumerable) that I gave the function as a parameter.

Somethig like this:

public class FooObject {
   private string Name;
   private List<FooObject>? Childs;
   
   public void RecursiveFunction(IEnumerable<FooObject> excludeList) {
      if (!excludeList.Any(x => x.Name == this.Name))
         return;

      excludeList = excludeList.Append(this);

      foreach (var child in this.Childs) {
         child.RecursiveFunction(excludeList);
      }
   }
}

The problem is that for example in a depth of 3 it appended an element to the list and has no child elements so finishes and goes up to depth 2 again and there the appended element from depth 3 isn't in the list anymore.

Is this behavior intended or do I missunderstand something in the concept of function parameters and pointers?

CodePudding user response:

You assign a different enumerable to the variable excludeList, similar as:

var excludeList = originalList; 
excludeList = otherList; // now originalList is not changed, of course

You need to let the method take a real list and use it's Add method

public void RecursiveFunction(List<FooObject> excludeList) {
  if (excludeList.Any(x => x.Name == this.Name))
     return;

  excludeList.Add(this);
  foreach (var child in this.Childs) {
     child.RecursiveFunction(excludeList);
  }
}

If you want to support more collection as just a List<T> you could allow ICollection<T>.

  •  Tags:  
  • c#
  • Related