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.
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:
StringBuilder
references, for example, then any changes to the objects themselves will still be visible.See more on this question at Stackoverflow