Partitioning Operators in Linq


In this article we will discuss about the partitioning operators in LINQ. Partitioning operators mean that to get some specific values from a collection. There are mainly four types of Partition Operators are there. 1. Take 2. Skip 3. TakeWhile 4. SkipWhile

In this article we will discuss about the partitioning operators in LINQ. There are mainly four types of partitioning operators in LINQ.
They are as follows :

1. Take
2. Skip
3. TakeWhile
4. SkipWhile


Now lets discuss all of them one by one.

Take Operator:

public void TakeExample()  
{
int[] values = { 4,8,5,8,4,6,4,5,4,7 };
var numbers = values.Take(5);
Console.WriteLine("First 5 numbers:");
foreach (var a in numbers)
{
Console.WriteLine(a);
}
}
//Output
First 5 numbers:
4
8
5
8
4


In this example we have an array of numbers, now using the "Take" operator, I am extracting the first 5 numbers from the array.

Skip Operator:

public void SkipExample() 
{
int[] values = { 4,8,5,8,4,6,4,5,4,7 };
var numbers = values.Skip(5);
Console.WriteLine("Skipping first 5 numbers:");
foreach (var a in numbers)
{
Console.WriteLine(a);
}

}
//Output
Skipping first 5 numbers:
6
4
5
4
7


In this example we have an array of numbers, now using the "Skip" operator, we are leaving the first 5 numbers and only extracting the next numbers.

TakeWhile Operator:

public void TakeWhileExample()  
{
int[] values = { 4,6,5,8,4,6,4,5,4,7 };
var numbers = values.TakeWhile(n=> n > 7);
Console.WriteLine("Using Take While:");
foreach (var a in numbers)
{
Console.WriteLine(a);
}
}
//Output
Using Take While:
4
6
5


In this example we have an array of numbers, now using the "TakeWhile" operator, we will print numbers from the beginning until a number is hit that is greater than 7.After hitting a number that is greater than 7, we will skip all numbers there after.

SkipWhile Operator:

public void SkipWhileExample()  
{
int[] values = { 4,6,5,8,4,6,4,5,4,7 };
var numbers = values.SkipWhile(n=> n > 7);
Console.WriteLine("Using Skip While:");
foreach (var a in numbers)
{
Console.WriteLine(a);
}
}
//Output
Using Skip While:
8
4
6
4
5
4
7


In this example we have an array of numbers, now using the "SkipWhile" operator, we will skip all the numbers from the beginning until a number is hit that is greater than 7.After hitting a number that is greater than 7, we will print all numbers there after.

If you have any queries regarding Partition Operators, you are free to ask.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: