public static IEnumerable<TSource> SkipWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Skips elements in a sequence as long as a specified condition is met and then returns the remaining elements.
Description
The SkipWhile
method skips elements in a sequence as long as the specified predicate
returns true
. Once the predicate returns false
for an element, that element and all subsequent elements are returned. If the predicate never returns false
, an empty sequence is returned.
This method performs deferred execution.
Parameters
- source [IEnumerable<TSource>]: The IEnumerable<TSource> to return elements from.
-
predicate
[Func<TSource, bool>]: A function to test each element for a condition. The method skips elements as long as the predicate returns
true
.
Returns
IEnumerable<TSource>: An IEnumerable<TSource> that contains the elements from the input sequence that occur after the first element for which the condition is false
.
Throws
- ArgumentNullException:
source
orpredicate
is null.
Remarks
The SkipWhile
method is the logical opposite of the TakeWhile
method. If you call TakeWhile
on a sequence, you get the elements from the beginning up to the first element that fails the predicate. If you call SkipWhile
on the same sequence, you get the elements from the first element that fails the predicate to the end.
This method does not modify the original sequence.
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int> { 5, 4, 3, 2, 1, 2, 3, 4, 5 };
// Skip numbers as long as they are greater than 3
IEnumerable<int> remainingNumbers = numbers.SkipWhile(n => n > 3);
Console.WriteLine("Original list:");
numbers.ForEach(Console.WriteLine);
Console.WriteLine("\nNumbers after skipping while greater than 3:");
foreach (int number in remainingNumbers)
{
Console.WriteLine(number);
}
// Output:
// Original list:
// 5
// 4
// 3
// 2
// 1
// 2
// 3
// 4
// 5
//
// Numbers after skipping while greater than 3:
// 3
// 2
// 1
// 2
// 3
// 4
// 5
}
}