Monday, July 30, 2012

C# LINQ - Take, Skip, TakeWhile, SkipWhile clauses

This post is part of a series called LINQ Examples that brings practical examples of using LINQ in C#.

Today we'll see practical examples of using Take, TakeWhile, Skip and SkipWhile clauses in LINQ. This kind of operators are called LINQ Partitioning Operators.
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    */

1 comment:

  1. nice post.. easy to understand...
    Thanks a lot.

    Vijay

    ReplyDelete