Does foreach evaluate the array at every iteration?

前端 未结 5 980
失恋的感觉
失恋的感觉 2020-11-27 20:34

I want to create a foreach which skips the first item. I\'ve seen elsewhere that the easiest way to do this is to use myCollection.Skip(1), but I h

5条回答
  •  攒了一身酷
    2020-11-27 21:32

    What's your iterating on is the result of the command:

    myCollection.Skip(1)
    

    This effectively returns an IEnumerable of the type of myCollection which has omitted the first element. So your foreach then is against the new IEnumerable which lacks the first element. The foreach forces the actual evaluation of the yielded Skip(int) method via enumeration (its execution is deferred until enumeration, just like other LINQ methods such as Where, etc.) It would be the same as:

    var mySkippedCollection = myCollection.Skip(1);
    foreach (object i in mySkippedCollection)
    ...
    

    Here's the code that Skip(int) actually ends up performing:

    private static IEnumerable SkipIterator(IEnumerable source, int count)
    {
        using (IEnumerator enumerator = source.GetEnumerator())
        {
            while (count > 0 && enumerator.MoveNext())
            {
                count--;
            }
            if (count <= 0)
            {
                while (enumerator.MoveNext())
                {
                    yield return enumerator.Current; // <-- here's your lazy eval
                }
            }
        }
        yield break;
    }
    

提交回复
热议问题