C# Linq TakeWhile() Method



Get elements as long as the condition is true in a sequence using the TakeWhile() method.

The following is our list with strings.

IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};

Now, let’s say we need the strings whose length is less than 4. For that, use Lambda Expressions and add it as a condition in the TakeWhile() method.

str.TakeWhile(a => a.Length < 4);

Here is the example that displays elements until the condition is trie.

Example

 Live Demo

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};
      var res = str.TakeWhile(a => a.Length < 4);
      foreach(var arr in res)
      Console.WriteLine(arr);
   }
}

Output

Car
Bus
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements