ForEach and List.Skip

Photo by Greg Rakozy on Unsplash

ForEach and List.Skip

I don't know if this happens to anyone else, but there are moments when I wonder if I know anything about programming. This usually happens when I am focused on the problem domain or figuring out how to structure my code using SOLID principles.

Today, I had a brain freeze on how the item "5" and not "8” was being returned when the Skip(3) was executed. I got it in my head that the Skip(3) would be executed multiple times in the foreach. It took some effort to get that wrong notion to leave my thought pattern.

Typing this out, it can be easier to see, but at the time I was busy juggling other logic threads in my noggin and the wrong thought about what was going on got all tangled up.

List<int> inputList = new List<int>();
inputList.Add(1);
inputList.Add(2);
inputList.Add(3);
inputList.Add(4);
inputList.Add(5);
inputList.Add(6);
inputList.Add(7);
inputList.Add(8);

foreach (int nextone in inputList.Skip(3))
{
}

In this case, inputList.Skip(3) is executed once when used in a foreach, the result is a list that is then looped over in the foreach. Therefore, the foreach will loop through all the resulting elements in the list after the Skip.