Linq中Take、TakeWhile、Skip、SkipWhile的比较

以下代码均来自微软官网
/// <summary>
/// This sample uses Take to get only the first 3 elements of the array.
/// </summary>
public void Linq1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var first3Numbers = numbers.Take(3); //从第一个元素开始,获取三个

Console.WriteLine("First 3 numbers:");

foreach (var n in first3Numbers)
{
Console.WriteLine(n);
}
}
result-----
First 3 numbers:
5
4
1

/// <summary>
/// This sample uses TakeWhile to return elements starting from the beginning
/// of the array until a number is hit that is not less than 6
/// </summary>
public void Linq2()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
//在这里需要注意.使用TakeWhile获取小于6的元素,是从第一个元素开始,
//一直到不满足其小于6这个条件为止.也就是执行到和9这个元素比较后,就结束比较了
//可以想象一下执行过程.
//5<6=true;4<6=true;1<6=true;3<6=true
//9<6=false; 这里就停止继续比较了
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);

Console.WriteLine("First numbers less than 6:");

foreach (var n in firstNumbersLessThan6)
{
Console.WriteLine(n);
}
}
result----
First numbers less than 6:
5
4
1
3


/// <summary>
/// This sample uses Skip to get all but the first 4 elements of the array
/// </summary>
public void Linq3()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst4Numbers = numbers.Skip(4); //跳过前四个元素,获取后面所有的元素

Console.WriteLine("All but first 4 numbers:");

foreach (var n in allButFirst4Numbers)
{
Console.WriteLine(n);
}
}
result---
All but first 4 numbers:
9
8
6
7
2
0

/// <summary>
/// This sample uses SkipWhile to get the elements of the array starting from the first element divisible by 3.
/// </summary>
public void Linq4()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

//跳过不能被3整除的所有元素
//这里和TakeWhiel又有些不一样。
//TakeWhile遇到条件不满足的时候,就会return,
//但是SkipWhile如果执行到能被三整除的数,那么其后面的元素就不会继续比较了
//同样,想象一下执行过程
//5%3!=0==true; 4%3!=0==true; 1%3!=0==true;
//3%3!=0==false; 运行到这里的时候,后面的就不再比较.
//所以输出结果中会有8、7、2、0这几个不满足条件的元素
var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);

Console.WriteLine("All elements starting from first element divisible by 3:");
foreach (var n in allButFirst3Numbers)
{
Console.WriteLine(n);
}
}
result---
All elements starting from first element divisible by 3:
3
9
8
6
7
2
0

你可能感兴趣的:(while)