TakeWhile Extension Method – I am amazed at how the C# language can teach me something new. I have come to the conclusion that it is basically impossible for a developer to know all there is about a given programming language (unless you are Jon Skeet of course). We learn as we need. I need to do xyz in code, so I research and find a way. Therefore I learn something new. The next time I will know how to do this. That is how we learn more about a particular language. Today I had a requirement to loop through a List<int> and stop the loop if the value in the list equaled zero. The TakeWhile Extension Method was the perfect fit.
TakeWhile Extension Method
So what would you do to ensure that while looping through a list of integers, that an integer equal to zero will stop the processing? I might have done something like this:
My requirement was slightly different though. I has been working on some legacy code and for some reason, the value zero was being added to the end of a permissions list. This permissions list was a list of user ID’s. Needless to say, zero was not a user ID that existed. I could implement the above foreach loop, but there is a better way and one that would probably speed up the loop (although I haven’t tested this). Go ahead and add the using statement to System.Linq if you don’t have it already.
Now you can add the TakeWhile Extension Method to your list right there in the foreach statement. This is much nicer and cleaner code than the alternative if condition above.
The lambda expression in the TakeWhile Extension method basically processes only the values not equal to zero. If it finds a zero, it will exit the foreach loop. Being a lambda expression, you can get very creative with your expression. Also remember, if you are using Visual Studio 2015, you can now debug lambda expressions! I thought this was just such a nice solution, one that I had to share. I hope someone can find it useful.
For more on this, have a look at the Enumerable.TakeWhile Method on MSDN as well as James Michael Hare’s excellent C#/.NET Little Wonders: Skip() and Take() article.
Edit: 15 Aug 2015
I have edited the article to clear up confusion regarding my requirement which was not to process all items not equal to zero, but to stop the loop if the value of zero was found. The list always contained a zero as the last integer in the permissions list and I needed to avoid processing a zero value. Thank you for all the comments.