接着上一篇:Linq中的Take和Skip (http://blog.csdn.net/joyhen/article/details/24504219)
TakeWhile:只要满足指定的条件,就会返回序列的元素。==>
TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) 方法使用 predicate 对 source 中的每个元素进行测试,如果结果为 true,则生成该元素。 当谓词函数对某个元素返回 false 或 source 中不再包含元素时,枚举将停止。
TakeWhile 和 SkipWhile 方法在功能上补充。 如果给定一个序列 coll 和一个纯函数 p,则连接 coll.TakeWhile(p) 和 coll.SkipWhile(p) 的结果会生成与 coll 相同的序列。
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
apple
banana
mango
SkipWhile: 只要满足指定的条件,就跳过序列中的元素,然后返回剩余元素
int[] grades = { 59, 82, 70, 56, 92, 98, 85 };
IEnumerable<int> lowerGrades =
grades
.OrderByDescending(grade => grade)
.SkipWhile(grade => grade >= 80);
Console.WriteLine("All grades below 80:");
foreach (int grade in lowerGrades)
{
Console.WriteLine(grade);
}
/*
This code produces the following output:
All grades below 80:
70
59
56
*/