Skip & SkipWhile in C# (System.Linq)

This blog is going to explain the Skip() and SkipWhile() method with small examples.

Skip() Method

From the sequence, the Skip(n) method will skip the first nth element and return the remaining element. If a sequence has five elements, and Skip(2), it will skip the first two elements and return the remaining three elements. The following figure illustrates how the skip method works.

The following is a code example of a Skip() method. The list collection contains 5 movie names, the Skip method skips 2 elements, so it returns the remaining three elements.

List<string> moviesList = new List<string>() { "Tangled", "Brave", "Frozen", "Zootopia", "Moana" };

var resultList = moviesList.Skip(2).ToList();

foreach (var movie in resultList)
{
Console.WriteLine(movie);
}

Output
Frozen
Zootopia
Moana

SkipWhile() Method
SkipWhile() skips the sequence of elements as long as the condition is true. If the condition is false, it will return the remaining elements. The following image illustrates the SkipWhile() method. There are five movie names in this sequence. The SkipWhile() method condition is x != "Zootopia", for the first three elements the condition is true. So it returns the 4th and 5th elements.
The following is a coding example of SkipWhile() method.


List<string> moviesList = new List<string>() { "Tangled", "Brave", "Frozen", "Zootopia", "Moana" };

var resultList = moviesList.SkipWhile(x => x != "Zootopia").ToList();

foreach (var movie in resultList)
{
Console.WriteLine(movie);
}

Output
Zootopia
Moana

I hope this article will help you. Keep coding


Related Article

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Creating a C# Azure Function with Visual Studio: Step-by-Step Guide

Exploring EventCallback in Blazor: Building Interactive Components