## Friday, February 4, 2011

### Partitioning LINQ Operator- Take, Skip, TakeWhile, SkipWhile

Partitioning Operator
Partitioning operators are,
Take
Skip
TakeWhile
SkipWhile.
Let’s begin with “Take”.

Take

Take operators takes given number of elements from a sequence (collection). I will explain with an example,
using System;
using System.Linq;

namespace ProjectionOperator
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var num = numbers.Take(5);
foreach (var number in num)
{
Console.WriteLine(number);
}
}
}
}

In the above example we have an integer array with number 1-10. Here “Take” operator take first five elements and skip the remaining. Simple.

SKIP
Skip is the reverse of "Take". Skip operator skips the first n numbers(n is the parametor to Skip method). Let's see with an example,

using System;
using System.Linq;

namespace Take_Skip_TakeWhile_SkipWhile
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var skipNumber = numbers.Skip(5);
Console.WriteLine("Skip the First 5 numbers ");
skipNumber.ToList().ForEach(a => Console.WriteLine(a));

}
}
}

Here Skip operator Skips first five number and select remaining.
So the output would be "6,7,8,9,10".

TakeWhile

TakeWhile take takes sequence in a collection until the mentioned condition is true. I will explain with an example.

Condider an array of numbers as below,

int[] randomNumbers = { 10, 6, 4, 8, 5, 3, 2, 1 };

consider a query like this,

randomNumbers.TakeWhile(a => a > 3)

output would be “10,6,4,8,5”. So TakeWhile takes numbers from a collection until the condition becomes false.

Whole line to print result using lambda is,

randomNumbers.TakeWhile(a => a > 3).ToList().ForEach(a => Console.WriteLine(a));

SkipWhile.

SkipWhile is the reverse of TakeWhile. SkipWhile skips sequence from a collection until the specified condition is true. I will explain with an example,

randomNumbers.SkipWhile(a => a > 3)

for the query the output would be “3,2,1” which means SkipWhile skip elements until the true condition met in a collection. Whole line to print result using lambda is ,

randomNumbers.SkipWhile(a => a > 3).ToList().ForEach(a => Console.WriteLine(a));