How to Use LINQ TakeWhile

Today I will talk about a simple and useful LINQ method called "TakeWhile". Enumerable.TakeWhile as defined on MSDN is a method that returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements. To show an example use of it, I provided a sample code that retrieve all numbers from a list that are less than 10 until it encounters a number greater or equal to 10.

int[] intnum = { 1, 3, 5, 7, 9, 11, 8, 9, 1, 2 };

var lessthan10 = intnum.TakeWhile(x => x < 10);

Console.WriteLine("Numbers that are less than 10.");
foreach (var x in lessthan10)
{
    Console.WriteLine(x);
}

The LINQ code above will produce the following result:

1
3
5
7
9

You can also apply it on a string list, as shown below.

string[] employees = { "auric", "rizza", "jayson", "fryan", "james", "cheesy" };

IEnumerable query =
    employees.TakeWhile(employee => String.Compare("fryan", employee, true) != 0);

foreach (string employee in query)
    Console.WriteLine(employee);

The LINQ code above will produce the following result:

auric
rizza
jayson

GD Star Rating
loading...
GD Star Rating
loading...
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply