How to use the iterating variable after a foreach

263 views Asked by At
foreach (var (counter, _, _) in Count())
{
    ... // do stuff with counter
}
return counter;

counter's out of scope after the foreach so the above doesn't work.

How can I use one of the iteration variables after a loop other than

int latestCounter;
foreach (var (counter, _, _) in Count())
{
    ... // do stuff with counter
    latestCounter = counter;
}
return latestCounter;
1

There are 1 answers

3
TimChang On

Call MoveNext() until last

    List<int> Count = new List<int>();
    IEnumerator<int> e = Count.GetEnumerator();
    if (e.MoveNext())
    {
        while (true)
        {
            var current = e.Current;
            bool anyNext = e.MoveNext();
            if (!anyNext)
            {
                // here in last
                break;
            }
        }
    }