foreach 循环中的无限 IEnumerable
回答这个问题后,我整理了遵循 C# 代码只是为了好玩:
public static IEnumerable<int> FibonacciTo(int max)
{
int m1 = 0;
int m2 = 1;
int r = 1;
while (r <= max)
{
yield return r;
r = m1 + m2;
m1 = m2;
m2 = r;
}
}
foreach (int i in FibonacciTo(56).Where(n => n >= 24) )
{
Console.WriteLine(i);
}
问题是我不喜欢需要将 max
参数传递给函数。 现在,如果我不使用它,代码将输出正确的数据,但随着 IEnumerable 继续工作,代码似乎会挂起。 我该如何编写这个以便我可以像这样使用它:
foreach (int i in Fibonacci().Where(n => n >= 24 && n <= 56) )
{
Console.WriteLine(i);
}
After answering this question I put together the following C# code just for fun:
public static IEnumerable<int> FibonacciTo(int max)
{
int m1 = 0;
int m2 = 1;
int r = 1;
while (r <= max)
{
yield return r;
r = m1 + m2;
m1 = m2;
m2 = r;
}
}
foreach (int i in FibonacciTo(56).Where(n => n >= 24) )
{
Console.WriteLine(i);
}
The problem is that I don't like needing to pass a max
parameter to the function. Right now, if I don't use one the code will output the correct data but then appear to hang as the IEnumerable continues to work. How can I write this so that I could just use it like this:
foreach (int i in Fibonacci().Where(n => n >= 24 && n <= 56) )
{
Console.WriteLine(i);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
SkipWhile
和TakeWhile
的组合。这些能够根据条件结束循环;
Where
流式传输其输入(适当过滤),直到输入用完(在您的情况下,永远不会)。You need to use a combination of
SkipWhile
andTakeWhile
instead.These are able to end loops depending on a condition;
Where
streams its input (filtering appropriately) until the input runs out (in your case, never).我认为除非您编写自己的 LINQ 提供程序,否则这是不可能的。 在您提供的示例中,您使用的是 LINQ to Objects,它需要完全评估 IEnumerable,然后才能对其应用过滤器。
I don't think this is possible unless you write your own LINQ provider. In the example you gave you are using LINQ to Objects which will need to completely evaluate the IEnumerable before it can apply a filter to it.