Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list in recursive function is getting reset

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading