Saturday 1 June 2013

LINQ – Skip() and Take() methods

I had this issue recently where I have an array of integers and I’m doing some Skip(n) and then a Take(m) on the collection. Here’s an abstraction of the code:
   1: int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
   2: var taken = numbers.Skip(3).Take(3);
   3: foreach (var i in taken)
   4: {
   5:     Console.WriteLine(i);
   6: }
The output is as expected: 3, 9, 8 – skip the first three and then take the next three items.
But, what happens if I do something like:
   1: var taken = numbers.Skip(7).Take(5);
In English – skip the first seven and the take the next 5 items from an array that contains only 10 elements. Think it’ll throw the IndexOutOfRangeException exception? Nope. These extension methods are a little smarter than that. Even though the user has requested more elements than what exists in the collection, the Take method only returns the first three thereby making the output of the program as: 7, 2, 0.
The scenario is handled similarly when you do:
   1: var taken = numbers.Take(5).Skip(7);
This one takes the first 5 elements from the numbers array and then skips 7 of them. This is what is looks like in the debug mode:
screen

0 comments:

Post a Comment


                                                            
 
Design by Abhinav Ranjan Sinha