本文介绍了C#无限迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中是否有与Java的Stream.iterate类似的东西?我能找到的最接近的东西是Enumerable.Range,但有很大的不同.

Is there anything similar in C# to Java's Stream.iterate? The closest thing I could find was Enumerable.Range but it is much different.

我问的原因是我一直在观看演示讲述了良好的编程原理,并且有一个关于声明式和命令式代码的线程.引起我注意的是一种可以生成伪无限数据集的方法.

The reason I'm asking is that I've been just watching some presentation about good programming principles and there was a thread about declarative vs. imperative code. What caught my attention was a way you can generate a pseudo-infinite set of data.

推荐答案

.Net框架中没有完全相同的等效项,但MoreLINQ库:

There isn't an exact equivalent in the .Net framework but there is one in the MoreLINQ library:

foreach (var current in MoreEnumerable.Generate(5, n => n + 2).Take(10))
{
    Console.WriteLine(current);
}

使用yield重新创建它也很简单:

It's also very simple to recreate it using yield:

public static IEnumerable<T> Iterate<T>(T seed, Func<T,T> unaryOperator)
{
    while (true)
    {
        yield return seed;
        seed = unaryOperator(seed);
    }
}

yield允许创建无限枚举器,因为:

yield enables to create an infinite enumerator because:

收益(C#参考)

这篇关于C#无限迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:23