我有一个 RekenReeks 类,它返回从 2 开始乘以 2 的数字。所以 {2,4,8,16,32,64}
现在我了解了 TakeWhile 和 SkipWhile 方法以及 LINQ。
所以我创建了 3 个变量,它们应该存储完全相同但我的 Console.WriteLine
只打印 selection1 而不是 2 和 3。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
RekenReeks reeks = new RekenReeks(2, n => n * 2);
var selection = from i in reeks
where i > 10
&& i < 1000
select i;
var selection2 = reeks.TakeWhile(n => n < 1000 && n > 10);
var selection3 = reeks.SkipWhile(n => n > 1000 && n < 10);
foreach (int i in selection)
{
Console.WriteLine("selection1 {0}",i);
}
foreach (int i in selection2)
{
Console.WriteLine("selection2 {0}", i);
}
foreach (int i in selection3)
{
Console.WriteLine("selection3 {0}", i);
}
Console.ReadLine();
}
}
public class RekenReeks : IEnumerable<int>
{
Func<int, int> getNew;
int number;
public RekenReeks(int starton, Func<int, int> getNewThing)
{
getNew = getNewThing;
number = starton;
}
public IEnumerator<int> GetEnumerator()
{
yield return number;
for (; ; )
{
yield return getNew(number);
number = getNew(number);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
最佳答案
您的序列是无限的(理论上)。你假设太多了。您的程序的功能不可能知道您的序列是严格单调递增的。
var selection = from i in reeks
where i > 10
&& i < 1000
select i;
这永远不会停止。因为 where
总是会提取下一个值,它不知道它的条件是否会得到满足,它总是必须检查下一个值。
var selection2 = reeks.TakeWhile(n => n < 1000 && n > 10);
这将采用介于 11 和 999 之间的值。由于您的序列以 2 开头,它将在第一个值处停止。
var selection3 = reeks.SkipWhile(n => n > 1000 && n < 10);
这将跳过介于 11 和 999 之间的值。由于第一个是 2,它不会跳过任何一个,因此产生所有。
关于C# - TakeWhile 和 SkipWhile 不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35653172/