TakeWhile
In this chapter you will learn:
- How to use TakeWhile operator
- TakeWhile with filter delegate
- Filter string array
- SkipWhile then TakeWhile
- TakeWhile by index
Get to know TakeWhile operator
TakeWhile
enumerates the input sequence,
emitting each item, until the given predicate is false.
It then ignores the remaining elements:
using System;//from j a v a2 s. co m
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 3, 5, 2, 7, 4, 1 };
var takeWhileSmall = numbers.TakeWhile(n => n < 5);
foreach(int s in takeWhileSmall){
Console.WriteLine(s);
}
}
}
The output:
TakeWhile with filter delegate
using System;//from jav a2 s . co m
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string[] names = { "Java", "C#", "Javascript", "SQL",
"Oracle", "Python", "C++", "C", "HTML", "CSS" };
IEnumerable<string> query = names.TakeWhile(n => n.Length < 5);
foreach(String s in query){
Console.WriteLine(s);
}
}
}
The output:
Filter string array
using System;//from j a v a 2s .co m
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"ant", "Hard", "Harrison", "Hayes", "Hoover", "Jack"};
IEnumerable<string> items = presidents
.TakeWhile((s, i) => s.Length < 10 && i < 5);
foreach (string item in items)
Console.WriteLine(item);
}
}
SkipWhile then TakeWhile
using System;/*from java2 s .c om*/
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
public class MainClass{
public static void Main(string[] args){
String[] TestData = {"One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight",
"Nine", "Ten"};
var ThisQuery =
TestData.SkipWhile(ThisElement => ThisElement != "Four").
TakeWhile(ThisElement => ThisElement != "Nine");
foreach (var ThisElement in ThisQuery)
Console.WriteLine(ThisElement);
}
}
TakeWhile by index
using System;// j av a2s . c o m
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = { 1, 3, 5, 4};
var query = numbers.TakeWhile(( n, index) => n >= index);
var query2 = numbers.SkipWhile(( n, index) => n >= index);
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Linq Operators