Back to: LINQ Tutorial For Beginners and Professionals
LINQ TakeWhile Method in C# with Examples
In this article, I am going to discuss LINQ TakeWhile Method in C# with Examples. Please read our previous article where we discussed the LINQ Take Method in C# with Examples. As part of this article, we are going to discuss the following pointers which are related to the LINQ TakeWhile Method in C#.
- What are the need and use of the LINQ TakeWhile Method in C#?
- Examples to Understand TakeWhile Method using both Method and Query Syntax.
- Understanding TakeWhile Method with Filtering Method.
- What is the difference between the Where and TakeWhile Methods in LINQ?
- LINQ TakeWhile Method with Complex Data Types.
What are the need and use of the LINQ TakeWhile Method in C#?
The LINQ TakeWhile Method in C# is used to fetch all the elements from a data source or a sequence or a collection until a specified condition is true. Once the condition is failed, then the TakeWhile method will not check the rest of the elements present in the data source even though the condition is true for some of the remaining elements. If this is not clear at the moment, then don’t worry, once we discussed the examples, then you will definitely understand this concept.
The point that you need to remember is that, like the Take Method, the LINQ TakeWhile Method will not make any changes to the positions of the elements in the data source. There are two overloaded versions available for this TakeWhile Method in C#. They are as shown in the below image.
The First version of the LINQ TakeWhile method returns elements from a sequence as long as the specified condition is true. Once the condition failed, then it will not check the remaining elements in the data source.
The Second Overloaded version of the TakeWhile 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 also not clear at the moment then don’t worry we will discuss this with an example.
Example to Understand LINQ TakeWhile Method in C#:
Let us see an Example to Understand LINQ TakeWhile Method in C# using both Method syntax and Query Syntax. 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. The point that you need to remember is, there is no such operator called take while available in LINQ to write the query syntax, So, here we need to use the mixed syntax which is shown in the below example.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { //Data Source List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Fetch Numbers which are less than 6 using TakeWhile Method //Using Method Syntax List<int> ResultMS = numbers.TakeWhile(num => num < 6).ToList(); //Using Query Syntax List<int> ResultQS = (from num in numbers select num).TakeWhile(num => num < 6).ToList(); //Accessing the Result using Foreach Loop foreach (var num in ResultMS) { Console.Write($"{num} "); } Console.ReadKey(); } } }
Output: 1 2 3 4 5
LINQ TakeWhile Method along with the Where Filtering Method in C#.
Now you may have one question in your mind, the same thing we can achieve using the LINQ Where extension method. For a better understanding, please have a look at the following example which uses the LINQ Where method.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { //Data Source List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Fetch Numbers which are less than 6 using Where Method //Using Method Syntax List<int> ResultMS = numbers.Where(num => num < 6).ToList(); //Using Query Syntax List<int> ResultQS = (from num in numbers where num < 6 select num).ToList(); //Accessing the Result using Foreach Loop foreach (var num in ResultQS) { Console.Write($"{num} "); } Console.ReadKey(); } } }
Output: 1 2 3 4 5
What is the Difference Between the Where and TakeWhile Method in LINQ?
Before understanding the difference between the LINQ Where and TakeWhile Extension Methods, let us first modify the Main method of the Program class as shown below and look at the output. Here we move the values 4 and 5 to the end of the collection or in the data source. That means the data source now stores the records in random order.
using System; using System.Collections.Generic; using System.Linq; namespace LINQDemo { class Program { static void Main(string[] args) { //Data Source: Numbers are Stored in Randon Order List<int> numbers = new List<int>() { 1, 2, 3, 6, 7, 8, 9, 10, 4, 5 }; //Using TakeWhile Method to Fetch Numbers which are less than 6 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 to Fetch Numbers which are less than 6 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:
As you can see in the above output, the LINQ TakeWhile method fetches the values 1, 2, and 3 while the LINQ Where method fetches the values 1, 2, 3, 4, and 5.
So, the difference between them is that the TakeWhile Extension 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, the TakeWhile method fetches the first three elements. When it checks the fourth element, 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 are present at the end of the collections) satisfy the condition.
On the other hand, the LINQ Where Extension Method checks each and every element present in the collection. The elements which satisfy the given condition will be returned as part of the result. It does not matter the position of the elements in the sequence.
Example to Understand TakeWhile Method with String Collection:
In the following example, we have a collection of names. Here, we need to return the names starting from the beginning until a name is hit that does not have a length greater than 3 characters. For this requirement, we should and must go with the TakeWhile Method instead of the Where Extension method.
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 to Understand TakeWhile Method which takes Index as a Parameter:
Let us use the other overloaded version of the LINQ TakeWhile Method which takes an index as a parameter. Here, in the following example, we check the length of the name should be greater than its index position. So, the first element index is 0, the second element index is 1, the third element index is 2, and so on. And then we are checking whether the length of the value is greater than its index position or not. If it is greater than its index position, then it will return true, else it will return false. In the data source, the fourth element i.e. Pam has a length of 3 and its index position is 3. So, here the condition is false and hence it will not check the rest of the elements in the data source. As a result, it only fetches the first three elements from the sequence.
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 next article, I am going to discuss the LINQ Skip Method in C# with Examples. In this article, I try to explain the LINQ TakeWhile Method in C# with Examples. We also discussed the difference between the LINQ Where and TakeWhile Extension Methods in C#. I hope you understood the need and use of the LINQ TakeWhile Method in C#.