C# SkipWhile Method

Skip illustration

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.

This C# example program uses the SkipWhile extension method. It requires System.Linq.

Example

To start, we declare an array that has several values in it: the first three elements are less than 10. Then, we call SkipWhile with a Func that returns true for elements less than 10. The end result is the first three elements in the array are skipped.

Program that shows SkipWhile method [C#]

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
Question and answer

Practical uses. What is a practical usage of the SkipWhile method? In your program, you might have some reason to remove elements at the start of a collection that begin with a certain letter or have a property set to a certain value. You could use SkipWhile; then, you could call ToArray to ToList to convert the IEnumerable back into an array or List.

ToArray ToList Array List

Summary

The C# programming language

In this example, we used the SkipWhile method, which is part of the System.Linq namespace. This method can help you remove elements that match a certain condition at the start of a collection. Please also check out the TakeWhile method.

TakeWhile LINQ Examples
.NET