TakeWhile Method in Linq

TakeWhile Method in Linq with Examples

In this article, I am going to discuss the TakeWhile Method in Linq with some examples. Please read our previous article before proceeding to this article where we discussed the Take Method with some examples. As part of this article, we are going to discuss the following pointers related to the TakeWhile Method in C#.

  1. What are the need and use of the TakeWhile Method in C#.NET?
  2. Examples using both Method and Query Syntax. 
  3. Understanding TakeWhile Operator with Filtering Operator.
  4. What is the difference between where and TakeWhile method in Linq?
  5. Different Types of examples using the TakeWhile Operator in Linq.
What are the need and use of the TakeWhile Method in C#.NET?

The TakeWhile Method in Linq is used to fetch all the elements from a data source or sequence until a specified condition is true. Once the condition is failed, then the TakeWhile method will not check the rest of the elements presents in the data source even though the condition is true for the remaining elements.

The TakeWhile method will not make any changes to the positions of the elements. There are two overloaded versions available for this method as shown in the below image.

TakeWhile Method in Linq

The First version of the TakeWhile method returns elements from a sequence as long as the specified condition is true.

The second overloaded version of this method returns elements from a sequence as long as the given condition is true. The second parameter of the function represents the index of the source elements. The element’s index can be used in the logic of the predicate function. If this is not clear at the moment then don’t worry we will discuss this with an example.

Example using TakeWhile Method in Linq:

In the following example, we created a data source that contains numbers from 1 to 10. Then we fetch the records from the data source using the TakeWhile method with the condition that the number is less than 6.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            
            List<int> ResultMS = numbers.TakeWhile(num => num < 6).ToList();
            
            foreach(var num in ResultMS)
            {
                Console.Write($"{num} ");
            }

            Console.ReadKey();
        }
    }
}

Output: 1 2 3 4 5

TakeWhile Method along with the Where Filtering Method in C#.NET.

Now you may have one question in your mind, that the same thing can be achieved using the Linq Where extension method as shown below.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            
            List<int> ResultMS = numbers.Where(num => num < 6).ToList();
            
            foreach(var num in ResultMS)
            {
                Console.Write($"{num} ");
            }

            Console.ReadKey();
        }
    }
}

Output: 1 2 3 4 5

What is the difference between where and TakeWhile method in Linq?

Before understanding the difference let us modify the program as shown below and look at the output. Here we move the values 4 and 5 to the end of the collection.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 6, 7, 8, 9, 10, 4, 5 };

            List<int> Result1 = numbers.TakeWhile(num => num < 6).ToList();
            Console.Write("Result Of TakeWhile Method: ");
            foreach (var num in Result1)
            {
                Console.Write($"{ num} ");
            }
            Console.WriteLine();

            //Using Where Method
            List<int> Result2 = numbers.Where(num => num < 6).ToList();
            Console.Write("Result Of Where Method: ");
            foreach (var num in Result2)
            {
                Console.Write($"{ num} ");
            }

            Console.ReadKey();
        }
    }
}

Output:

Difference between Where and TakeWhile method in Linq

As you can see in the above output, the “TakeWhile” method fetches the values 1, 2, and 3 while the “Where” method fetches the values 1, 2, 3, 4, and 5.

So, the difference is that the TakeWhile method checks the conditions from the beginning of the data source. As long as the condition is true it fetches the data. So, in our example, for the first three elements, the condition is true so it fetches the first three elements. When it checks the fourth elements the condition becomes false. So from that point, it will not check the rest of the elements in the data source even though some of the elements (i.e. 4 and 5 present at the end of the collections) satisfying the condition.

On the other hand, the Where method checks each and every element present in the collection. The elements which satisfy the condition will be returned. It does not matter the position of the elements in the sequence.

Example:

In the following example, we have a collection of names. Here, we need to return names’ starting from the beginning until a name is hit that does not have a length greater than 3 characters.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "Sara", "Rahul", "John", "Pam", "Priyanka" };

            List<string> namesResult = names.TakeWhile(name => name.Length > 3).ToList();
            
            foreach (var name in namesResult)
            {
                Console.Write($"{ name} ");
            }
            
            Console.ReadKey();
        }
    }
}

Output: Sara Rahul John

Example:

Let us use the other overloaded version which takes an index as a parameter. Here, in the following example, we will check the length of the name should be greater than its index position.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string>() { "Sara", "Rahul", "John", "Pam", "Priyanka" };

            List<string> namesResult = names.TakeWhile((name, index) => name.Length > index).ToList();
            
            foreach (var name in namesResult)
            {
                Console.Write($"{ name} ");
            }
            
            Console.ReadKey();
        }
    }
}

Output: Sara Rahul John

In the sequence the fourth element i.e. Pam has length 3 and its index position is 3. So, here the condition is false and hence it will not check the next element. As a result, it only fetches the first three elements from the sequence.

In the next article, I am going to discuss the Skip method in Linq with some examples. In this article, I try to explain the TakeWhile method and the difference between where and TakeWhile method. I hope you understood the need and use of the TakeWhile method in Linq.

Leave a Reply

Your email address will not be published. Required fields are marked *