您的位置:首页 > 其它

Linq中的TakeWhile和SkipWhile的用法

2015-08-21 11:11 483 查看
Linq中的SkipWhile

1、含义

(1)、对数据源进行枚举,从第一个枚举得到的元素开始,调用客户端的predicate
(2)、如果返回true,则跳过该元素,继续进行枚举操作.
(3)、但是,如果一旦predicate返回为false,则该元素以后的所有元素,都不会再调用predicate,而全部枚举给客户端.

2、实例

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
*/


二、Linq中的TakeWhile

1、含义

(1)、对数据源进行枚举,从第一个枚举得到的元素开始,调用客户端传入的predicate( c.Name == ""woodyN")
(2)、如果这个predicate委托返回true的话,则将该元素作为Current元素返回给客户端,并且,继续进行相同的枚举,判断操作.
(3)、但是,一旦predicate返回false的话,MoveNext()方法将会返回false,枚举就此打住,忽略剩下的所有元素.

2、实例

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
*/


参考资料:Linq中的TakeWhile和SkipWhile http://www.studyofnet.com/news/872.html
本文出自 “学习也休闲” 博客,请务必保留此出处http://studyofnet.blog.51cto.com/8142094/1686772
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: