.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Lambda Expressions Extension Method 4 - TakeWhile()

Posted By:Jean Paul       Posted Date: May 06, 2011    Points: 200    Category: LINQ    URL: http://www.dotnetspark.com  

Lambda Expressions Extension Method 4 - TakeWhile()


The method TakeWhile() is a tricky method.  It will take a condition as parameter and it will return the elements until the condition is true and exists the iteration. 

It is not similar to Where() condition.  Let me take an example.  We have  1, 2, 3, 4, 5, 6 in the list and given a condition TakeWhile(i => I != 2) it will return just 1.  The method works like below:

It will go through element 1 and as it satisfies the condition it will be yield returned. 

On the second element 2  the condition is false and it will exits.

There is no processing for element 3.

Arguments: Condition

Return Value: List of Items


In the following example we are using a list of integers and the Take() method to select the top n numbers from the list.

        private IList<int> _list = new List<int>();


        public InitializeList()


            // Set data









        private void TakeWhileButton_Click(object sender, EventArgs e)


            /// TakeWhile method to get a sublist based on condition

            var result = _list.TakeWhile(i => i != 2);


            foreach (int i in result)




Extension Method Snapshot

You can find the snapshot of the TakeWhile() method usage as provided by Visual Studio

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend