重复枚举无限期 [英] Repeat an enumerable indefinitely

查看:171
本文介绍了重复枚举无限期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有重复枚举无限期枚举扩展方法?

Is there an enumerable extension method that repeats the enumerable indefinitely?

因此,例如,给定返回一个枚举:[一,B,C]。我想,返回一个无限的重复序列[一个的方法,B,C,一个,B,C,一个,B,C... ]

So for example, given an enumerable that returns: ["a", "b", "c"]. I would like a method that returns an infinite repeating sequence ["a", "b", "c", "a", "b", "c", "a", "b", "c" ... ]

这听起来有点像的 Observable.Repeat ,但我想在IEnumerables操作。

This sounds a bit like Observable.Repeat, except I would like to operate on IEnumerables.

Enumerable.Repeat 只生成由单一元素的枚举。

Enumerable.Repeat only generates an enumerable from a single element.

推荐答案

我不知道任何东西建到LINQ,但它的真正的轻松创建自己的:

I don't know of anything built into LINQ, but it's really easy to create your own:

public static IEnumerable<T> RepeatIndefinitely<T>(this IEnumerable<T> source)
{
    while (true)
    {
        foreach (var item in source)
        {
            yield return item;
        }
    }
}

请注意,这个评估多次 - 你的 的可能要使它只能这样做一次,创建一个副本:

Note that this evaluates source multiple times - you might want to make it only do so once, creating a copy:

public static IEnumerable<T> RepeatIndefinitely<T>(this IEnumerable<T> source)
{
    var list = source.ToList();
    while (true)
    {
        foreach (var item in list)
        {
            yield return item;
        }
    }
}



注:

Notes:


  • 创建序列的拷贝意味着原来的顺序可以自由而不用担心这个代码遍历它同时被修改。

  • 创建序列的拷贝意味着它需要足够小,以适应在存储器,当然。这可能不是很理想。

  • 当你开始遍历结果这只会创建一个副本。这很容易令人惊讶。另一种方法是将有哪些创建一个副本,然后委托给私人iterator方法非迭代方法。这是用于在LINQ参数验证的办法

  • 副本是浅 - 如果来源是的StringBuilder 引用的序列,例如,然后到对象的任何变化本身仍将是可见的。

  • Creating a copy of the sequence means the original sequence may be modified freely without worrying about this code iterating over it concurrently.
  • Creating a copy of the sequence means it needs to be sufficiently small to fit in memory, of course. That may not be ideal.
  • This will only create a copy when you start iterating over the result. That could easily be surprising. An alternative approach would be to have a non-iterator method which created a copy, then delegated to a private iterator method. This is the approach used for argument validation in LINQ.
  • The copy is shallow - if the source is a sequence of StringBuilder references, for example, then any changes to the objects themselves will still be visible.

这篇关于重复枚举无限期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆