using System;
using System.Linq;
// Step 1: create array for demonstration.
int[] array = { 1, 3, 5, 7, 9, 11 };
// Step 2: get collection of all elements except first two.
var items1 = array.Skip(2);
foreach (var value in items1)
{
Console.WriteLine("SKIP 2: {0}", value);
}
// Step 3: call Skip again but skip the first 4 elements.
var items2 = array.Skip(4);
foreach (var value in items2)
{
Console.WriteLine("SKIP 4: {0}", value);
}SKIP 2: 5
SKIP 2: 7
SKIP 2: 9
SKIP 2: 11
SKIP 4: 9
SKIP 4: 11
SkipWhile. This method skips over elements matching a condition. With SkipWhile you need to specify a Func condition to skip over values with.
Start We declare an array that has several values in it. The first 3 elements are less than 10.
And We call SkipWhile with a Func that returns true for elements less than 10. The first 3 elements in the array are skipped.
using System;
using System.Linq;
int[] array = { 1, 3, 5, 10, 20 };
var result = array.SkipWhile(element => element < 10);
foreach (int value in result)
{
Console.WriteLine(value);
}10
20
Practical uses. 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.
Tip You could use SkipWhile. Then you could call ToArray to ToList to convert the IEnumerable back into an array or List.
Discussion. The Skip extension method is a generic method, which means it requires a type parameter. The C# compiler can infer the correct type parameter.
Tip 2 Often you would use Skip on a collection that cannot be accessed by specific indexes.
Skip and Take. You can also use the Skip extension method in query method chains. Often you may want to combine it with Take, either before the Skip or after.
Note The Take extension method specifies that you only want to access the following several elements.
So If you want the middle elements in a sequence, you can Skip over the first several and then Take the part you want.
A summary. Skip serves to "pass over" several elements in any class that implements the IEnumerable interface. It is most useful on more complex collections or queries.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 26, 2023 (edit).