Skip
This is an extension method. It returns only the elements following a certain number of initial elements that must be ignored.
Skip
namespaceSkip()
is found in the System.Linq
namespace. It is useful in programs that selectively process elements. SkipWhile
is also available.
Please include the System.Linq
namespace. This provides extensions that act upon IEnumerable
implementations (like arrays and Lists).
Skip()
is the int
2. This will pass over the first 2 elements and only return those that follow.Skip()
takes effect when the foreach
queries for results.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.
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
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.
SkipWhile
. Then you could call ToArray
to ToList
to convert the IEnumerable
back into an array or List
.The Skip()
extension method is a generic method, which means it requires a type parameter. The C# compiler can infer the correct type parameter.
Skip()
extension method internally allocates a new class
that is compiler-generated and stores the state of the Skip
operation.for
-loop and starting at the desired index will be much faster.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.
Take()
extension method specifies that you only want to access the following several elements.Skip()
over the first several and then Take
the part you want.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.