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
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;
}