Do Enumerable.ElementAt in the same iteration of Enumerable

I'm iterating through an IEnumerable like below.

IEnumerable<string> readFile = ... ;
int lineNumber = 1;

foreach (string readLine in readFile)
{
   ...

   lineNumber++;
}

But during the loop I have to check the next line. And I use ElementAt for this:

foreach (string readLine in readFile)
{
   ...
   if (readFile.ElementAt(lineNumber+1) == ...)
   {
      // Do something
   }

   lineNumber++;
}

When I use the above code with ElementAt, I get Possible multiple enumeration of IEnumerable

Can you explain this to me? Or is there another solution I can use? I have to use IEnumerable because I'm working with large files

Jon Skeet
people
quotationmark

Well any time you call ElementAt, if it's just a sequence (i.e. not an IList<T>) it will have to iterate all the way through the sequence as far as the given element number - there's no other way of it getting to the value.

It sounds like you should just have:

string previousLine = null;
foreach (var line in readFile)
{
    // Work with line and previousLine here, understanding that on the
    // first iteration it will be null

    previousLine = line;
}

people

See more on this question at Stackoverflow