2

I am trying to use recursion to go up a hierarchy, and i get this error:

Collection was modified; enumeration operation may not execute.

My assumption here is that when it enters the function each time, it is using the same parentRolesCopy and not a different one, so when it enters in the second time it changes parentRolesCopy to be different in the original function call.

How can I get around this?

private IEnumerable<string> GetAllParentRoles(string role)
    {
        // GET EACH PARENT ROLE
        var parentroles = //code that gets any parents of the role passed in


        //RECURSIVELY CALL THIS FUNCTION TO KEEP GETTING PARENTS OF PARENT ROLES UNTIL NONE LEFT
        var parentRolesCopy = parentroles;
        foreach (var parentrole in parentRolesCopy)
        {
            parentroles.AddRange(GetAllParentRoles(parentrole));
        }

        return parentroles;
    }
Kyle
  • 32,731
  • 39
  • 134
  • 184

2 Answers2

4

You can make the copy actually be a copy instead of just pointing to the same reference. One way would be:

var parentRolesCopy = parentroles.ToArray();
itsme86
  • 19,266
  • 4
  • 41
  • 57
  • Ah, thanks! I didn't realize what I was doing was just making a reference to the original. – Kyle Aug 29 '12 at 17:11
2

You can use List or some other collection

var parentRolesCopy = new List<string>(parentroles);
L.B
  • 114,136
  • 19
  • 178
  • 224