Introduction:

 

In this article we will learn, how to TakeWhile method in LINQ or what is TakeWhile method in LINQ C# Asp.net MVC with example.

Description:

In LINQ, The TakeWhile() method is used to get the elements from list or collection based on the condition specified.  The TakeWhile()method returns elements from the given collection until the specified condition is true. If the first element itself doesn't satisfy the condition then returns an empty collection.

 

 

Example of LINQ TakeWhile() Method

 

Following is the example of using LINQ TakeWhile() in method to get elements from list / collection based on condition.

 

 using System;
using System.Collections.Generic;
using System.Linq;
namespace SQLTutorialsPoint
{
    class Employee
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> Employee = new List<Employee>(){
            new Employee() {  Name = "Suresh",ID  = 1},
            new Employee() {  Name = "Sekher", ID=  2 },
              new Employee() {  Name = "Sumit", ID=  3 },
            new Employee() {  Name = "Pankaj", ID = 4},
            new Employee() {  Name = "Suraj", ID = 5}};
 
            var result = Employee.TakeWhile(x => x.Name.StartsWith("S"));
 
            foreach (var item in result)
            {
                Console.WriteLine("Employee Name:"+item.Name+"  ID:" + item.ID);
            }
 
            Console.ReadLine();
        }
    }
}

 

 

As you see above example we used TakeWhile () method and a lambda expression in which we specified that it selects only the employee that Name starts with “S”. So it will return elements till the condition holds true for the items in list or collection.

 

Now we will run and see the output.

 Use TakeWhile Operator or Method in LINQ

 

In this article we learned, how we can use LINQ TakeWhile() partition operator in method syntax / query syntax to get elements from sequence in list / collection based on the condition we defined in expression.

 

I hope it will help to you after reading.

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like