This
post is the part of series called LINQ
Operators that brings the practical examples of LINQ operators. In previous
posts we have learned about Filtering and Projection operators.Today we will
see the Partition Operators in LINQ.
Partitioning Operators:
The
Skip,
Take, TtakeWhile and SkipWhile are the primary LINQ Partitioning Operators. These operators are commonly used to
produced paged result-sets for UI data binding. In order to get the third page
of results for a UI that shows 10 records per page, you could apply a Skip(20)
operator followed by a Take(10).
Examples:
int[] numbers = { 1, 3, 9, 8, 6, 7, 2, 0, 5, 10 };
var firstFive = numbers.Take(5);
Console.WriteLine("First five
numbers:");
foreach (var x in firstFive)
Console.Write(x + ",
"); /* Output: 1, 3, 9, 8, 6 */
var skipFive = numbers.Skip(5);
Console.WriteLine("All but
first five numbers:");
foreach (var x in skipFive)
Console.Write(x + ",
"); /* Output: 7, 2, 0, 5, 10 */
var firstLessThanFive = numbers.TakeWhile(n => n < 5);
Console.WriteLine("First
numbers less than five:");
foreach (var x in firstLessThanFive)
Console.Write(x + ",
"); /* Output: 1, 3
*/
var fromFirstEven = numbers.SkipWhile(n => n % 2 != 0);
Console.WriteLine("All elements
starting from first even element:");
foreach (var x in fromFirstEven)
Console.Write(x + ",
"); /* Output: 8, 6, 7, 2, 0, 5, 10 */
Happy reading!!
No comments:
Post a Comment