top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain what is the difference between Skip() and SkipWhile() extension method?

+3 votes
694 views
Explain what is the difference between Skip() and SkipWhile() extension method?
posted Apr 20, 2015 by Muskan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Skip() : It will take an integer argument and from the given IEnumerable it skips the top n numbers

SkipWhile (): It will continue to skip the elements as far as the input condition is true. It will return all remaining elements if the condition is false

Skip is an extension method. It returns only the elements following a certain number of initial elements that must be ignored. It is found in the System.Linq namespace. It is useful in programs that selectively process elements.

Example Skip:

To start, you must include the System.Linq namespace. This provides the extension methods that act upon the IEnumerable implementations found in many common types such as arrays and Lists.

C# program that uses Skip method from LINQ

using System;
using System.Linq;    
class Program
{
    static void Main()
    {
    //
    // Array that is IEnumerable for demonstration.
    //
    int[] array = { 1, 3, 5, 7, 9, 11 };
    //
    // Get collection of all elements except first two.
    //
    var items1 = array.Skip(2);
    foreach (var value in items1)
    {
        Console.WriteLine(value);
    }
    //
    // Call Skip again but skip the first four elements this time.
    //
    var items2 = array.Skip(4);
    foreach (var value in items2)
    {
        Console.WriteLine(value);
    }
    }
}

Output

5      The first two numbers in the array are missing.
7
9
11

9      The first four numbers are skipped.
11

Skip While:

SkipWhile skips over elements matching a condition. This method is provided in the System.Linq namespace for the C# language. With SkipWhile you need to specify a Func condition to skip over values with.

C# program that shows SkipWhile method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
    int[] array = { 1, 3, 5, 10, 20 };
    var result = array.SkipWhile(element => element < 10);
    foreach (int value in result)
    {
        Console.WriteLine(value);
    }
    }
}

Output

10
20
answer Apr 20, 2015 by Shivaranjini
...