LINQ – TakeWhile and SkipWhile methods
- by nmarun
I happened to read about these methods on Vikram's blog and tried testing it. Somehow when I saw the output, things did not seem to add up right. I’m writing this blog to show the actual workings of these methods. Let’s take the same example as showing in Vikram’s blog and I’ll build around it. 1: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
2:
3: foreach(var number in numbers.TakeWhile(n => n < 7))
4: {
5: Console.WriteLine(number);
6: }
Now, the way I (incorrectly) read the upper bound condition in the foreach loop was: ‘Give me all numbers that pass the condition of n<7’. So I was expecting the answer to be: 5, 4, 1, 3, 2, 0. But when I run the application, I see only: 5, 4, 1,3. Turns out I was wrong (happens at least once a day).
The documentation on the method says ‘Returns elements from a sequence as long as a specified condition is true. To show in code, my interpretation was the below code’:
1: foreach (var number in numbers)
2: {
3: if (number < 7)
4: {
5: Console.WriteLine(number);
6: }
7: }
But the actual implementation is:
1: foreach(var number in numbers)
2: {
3: if(number < 7)
4: {
5: Console.WriteLine(number);
6: break;
7: }
8: }
So there it is, another situation where one simple word makes a difference of a whole world.
The SkipWhile method has been implemented in a similar way – ‘Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements’ and not ‘Bypasses elements in a sequence where a specified condition is true and then returns the remaining elements’. (Subtle.. very very subtle).
It’s feels strange saying this, but hope very few require to read this article to understand these methods.