Take and TakeWhile Partitioning Operators, in this tutorial we learn how when to use Take and TakeWhile extension methods in LINQ.
you must add following required namespace in your class.
using System; using System.Collections.Generic; using System.Linq; using System.Data;
Any partitioning operators split the sequence of any collection into two parts and returns one part.
Let’s look at some examples of Take method
LINQ Take method with a int list
IList<int> intList = new List<int>() { 10, 20, 30, 50, 70, 90, 45, 55 }; IEnumerable<int> _result= intList.Take(5); foreach (int i in _result) { Console.WriteLine(i); }
if you execute the above code the result would be first five numbers
10 20 30 50 70
Here is another example of LINQ Take() method with a string array
string[] strArray = new string[] { "India", "USA", "UK", "Canada", "Australia" }; IEnumerable<string> _result1 = strArray.Take(2); foreach (string s in _result1) { Console.WriteLine(s); }
Now we look at LINQ TakeWhile method example
TakeWhile method returns elements of any given collection until the specified condition is satisfied.
IList<int> intList = new List<int>() { 10, 20, 30, 50, 70, 90, 45, 55 }; IEnumerable<int> _result= intList.TakeWhile(i=> i <=50 ); foreach (int i in _result) { Console.WriteLine(i); }
Here is the result, condition (i less than or equal to 50 )
10 20 30 50
Here is another example of LINQ TakeWhile() method with a string array
string[] strArray = new string[] { "India", "USA", "UK", "Canada", "Australia" }; IEnumerable<string> _result1 = strArray.TakeWhile(s => s.Length >= 3); foreach (string s in _result1) { Console.WriteLine(s); }
Note: We cannot write Take and TakeWhile operator using query syntax in C#