Search code examples
c#enumerator

C# Error Additional information: The enumeration has already completed


This is my first time using the enumerator interface. I am Trying to look threw a stack to find next occurrence of a string. The loop is suppose to loop threw my tags stack and find out if a tag inside my stack is a tag i was looking for. Once the stack gets to the last tag in the stack it crashes and issues the error in the title. The last tag in the list also happens to be the first match for lookforthisTag string variable. I want the while look to exit when the if statement finds a match or when all stack items have been compared.

/*find next opening tag in stack */
int I = 1;
var enumerator = tags.GetEnumerator(); /// create a enumerator variable 

/// move to the next tag in stack 
while ( enumerator.MoveNext() != false || found == true || I <= countofTags)    
{                                                    
      htmlTags currentTag = enumerator.Current; // this line causes error.
      if (currentTag.open_tag == lookforthisTag)
      {
              found = true;                                 
      }
I++;  
}///End while.    

Solution

  • This line

    while ( enumerator.MoveNext() != false || found == true || I <= countofTags)    
    

    will execute the following logic

    • Does the enumerator returns true? If yes enter the loop else check next condtion
    • Is found == true? If yes enter the loop, else check the next condition
    • Is I <= countofTags? If yes enter the loop, else exit the loop

    As you can see even when the enumerator return false it enters the loop because at that point found is true, but inside the loop you call enumerator.Current and this triggers the error message.

    Probably you want

    while ( !found && enumerator.MoveNext() && I <= countofTags)   
    

    Consider that a normal foreach loop would do the same

    htmlTags found = null;
    foreach(htmlTags currentTag in tags)
    {
       if (currentTag.open_tag == lookforthisTag)
       {
              found = currentTag;                                 
              break;
       }
    }
    if(found != null)
    {
        // got it...
    }
    

    or just using Linq

    htmlTags found = tags.FirstOrDefault(x => x.open_tag == lookforthisTag)
    if(found != null)
    {
        // you have found your tag.
    }
    

    I want also to mention the fact that your I <= countOfTags logic doesn't seem to have any utility in the code shown. The variable I will be always equal to the countOfTags (or just simply equal to tags.Count) because you don't break the loop and continue till the end of the enumeration. If you want to know the 'position' of the found tag, just increment it.