Summary: in this tutorial, you will learn how to use the LINQ SkipWhile()
method to bypass elements in a sequence until a specified condition is no longer met.
Introduction to the LINQ SkipWhile() method
The LINQ SkipWhile()
method allows you to bypass elements in a sequence until a specified condition is no longer true:
IEnumerable<T> SkipWhile<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
Code language: C# (cs)
The SkipWhile()
method takes two parameters:
source
is an input sequence of elements.predicate
is a function that defines the condition evaluated for each element in the source sequence.
The SkipWhile()
method skips elements until the predicate function returns false for an element. It returns a new IEnumerable<TSource>
that contains all the remaining elements.
LINQ SkipWhile() method example
The following example uses the SkipWhile()
method to skip elements until it finds an element that is greater than 5 and returns the remaining elements:
using static System.Console;
var numbers = new List<int> { 1, 2, 3, 6, 7, 8, 4, 9 };
var result = numbers.SkipWhile(x => x <= 5);
foreach (var number in result)
{
WriteLine(number);
}
Code language: C# (cs)
Output:
6
7
8
4
9
Code language: C# (cs)
In this example, the SkipWhile()
skips numbers 1, 2, and 3 because they make the condition <= 5 true. It returns the remaining numbers 6, 7, 8 4, and 9.
LINQ SkipWhile vs Where
The following table illustrates the differences between the SkipWhile()
and Where()
methods:
Criteria | SkipWhile | Where |
---|---|---|
Purpose | Skips elements until a condition becomes false | Evaluates the condition independently for each element |
Condition Evaluation | Evaluates the condition independently for each element | Evaluates condition independently for each element |
Usage | Skip initial elements until a condition is met | Filter elements based on a specific condition |
Result | Returns remaining elements after the condition is false | Returns elements that satisfy the condition |
Summary
- Use the LINQ
SkipWhile()
method to skip initial elements until a condition is met and return the remaining elements in a sequence.