Summary: in this tutorial, you’ll learn how to use the LINQ Skip()
method to skip a specified number of elements and return the remaining elements.
Introduction to the LINQ Skip() method
The LINQ Skip()
method skips a specified number of elements and returns the remaining elements in a sequence. Here’s the syntax of the Skip()
method:
IEnumerable<TSource> Skip<TSource>(
this IEnumerable<TSource> source,
int count
);
Code language: C# (cs)
In this syntax:
TSource
is the type of elements of the source sequence.source
is a sequence with theIEnumerable<TSource>
type.count
is the number of elements to skip.
The Skip()
returns a sequence with the IEnumerable<T>
type that contains the elements after the specified index in the source sequence.
The Skip()
method is implemented using deferred execution. It means that the query returned by the Skip()
method will not be executed until it is iterated by a foreach
loop or by calling its GetEnumerator()
method.
In practice, you often use the Skip()
method with the Take()
method. The Skip()
method skips a specified number of elements and the Take()
method retrieves a specified number of elements returned by the Skip()
method.
LINQ Skip() method examples
Let’s take some examples of using the Skip()
method.
1) Using LINQ Skip() method to skip some elements and return the remaining elements
The following program demonstrates how to use the Skip()
method to skip some elements and return the remaining elements:
using static System.Console;
int[] scores = { 1, 2, 3, 4, 5 };
var results = scores.Skip(2);
foreach (var result in results)
{
WriteLine(result);
}
Code language: C# (cs)
In this example, we use the Skip()
method to skip the first two elements of the scores
array and return the remaining elements (3,4, and 5). Then, we assign the resulting sequence to the results
variable, use a foreach
loop to iterate over the elements, and write each to the console.
2) Using LINQ Skip() method with the Take() method
The program demonstrates how to use the Skip()
and Take()
methods to retrieve a subset of elements from a string array:
using static System.Console;
string[] fruits = { "Apple", "Orange", "Banana", "Cherry", "Mango" };
var results = fruits.Skip(2).Take(2);
foreach (var result in results)
{
WriteLine(result);
}
Code language: C# (cs)
How it works.
First, define an array of strings called fruits
that has five elements.
Second, use the Skip()
method to skip the first two elements of the fruits
array and return the remaining elements and the Take()
method to take two elements from the sequence returned by the Skip()
method.
Third, iterate over the elements of the resulting sequence results
and write each to the console.
Summary
- Use the
Skip()
method to skip a specified number of elements and return the remaining elements of a sequence. - Chain the
Skip()
method with theTake()
method to retrieve a range of elements of a sequence.