Repeat an enumerable indefinitely

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

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" ... ]

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

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

Jon Skeet
people
quotationmark

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:

  • 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.

people

See more on this question at Stackoverflow