Tuesday, 8 September 2015

How to Use Take/TakeWhile and Skip/SkipWhile in LINQ

  int[] arr = { 1, 3, 11, 6, 8, 2, 6,};

Take=> Its work like Top keyword in SQL . See below ex

 var Take = arr.Take(2);

//its will return IEnumerable collection 

Output-1,3


TakeWhile=> TakeWhile will return the collection having a value of less than 10 , like on second position we have 11 , so it will break and it will return only 1,3 as output .

          var TakeWhile = arr.TakeWhile(item => item < 10);

            foreach (var item in TakeWhile )
            {
                Console.WriteLine(item );

            }

Output-1,3


Skip=> The Skip method will skip the  items from the collection and return the remaining items as an IEnumerable collection.
like i have skip first element of array
        var Skip = arr.Skip(1);
          foreach (var item in Skip)
            {
                Console.WriteLine(item );
            }

Output-3,11, 6, 8, 2, 6

SkipWhile=>SkipWhile operator will skip the items from the starting position until the conditions fails. Once the condition has failed then it will return the remaining items as an IEnumerable collection.

var SkipWhile = arr.SkipWhile(item => item < 10);

  foreach (var item in SkipWhile )
            {
                Console.WriteLine(item );
            }

Output-11, 6, 8, 2, 6






No comments:

Post a Comment