LINQ – Skip() and Take() methods

Posted by nmarun on ASP.net Weblogs See other posts from ASP.net Weblogs or by nmarun
Published on Tue, 13 Apr 2010 17:14:11 GMT Indexed on 2010/04/13 17:23 UTC
Read the original article Hit count: 183

Filed under:
|

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

Just wanted to share this behavior.

© ASP.net Weblogs or respective owner

Related posts about c#

Related posts about LINQ