Take & TakeWhile in C# (System.Linq)


This blog is going to explain Take() and TakeWhile() with small examples. 

Take() metod
From the sequence, the Take(n) method will return the first nth element. For example, if there are 5 elements in the list, then Take(2) will get the first 2 elements. The following image illustrates how the Take() method works.


The following is the demo code. The moviesList variable has a list of 5 movie names. The take() method take(2) takes the first 2 movie names.

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

var resultList = moviesList.Take(2);

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

Output
Tangled
Brave

TakeWhile() metod
The TakeWhile() method returns the elements until the condition is true. In the following example, five movie names are assigned to the moviesList variable. And x != "Zootopia" condition has been checked. So the result will be  "Tangled", "Brave", "Frozen". Because the first 3 elements are not equal to "Zootopia". The fourth element is equivalent to  "Zootopia", so the condition is false, so it returns the first 3 movie names.


The following is a code example

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

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

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

Output
Tangled
Brave
Frozen

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

Exploring EventCallback in Blazor: Building Interactive Components

A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC