How to repeat whole IEnumerable
multiple times?
Similar to Python:
> print ['x', 'y'] * 3
['x', 'y', 'x', 'y', 'x', 'y']
You could use plain LINQ to do this:
var repeated = Enumerable.Repeat(original, 3)
.SelectMany(x => x);
Or you could just write an extension method:
public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source,
int count)
{
for (int i = 0; i < count; i++)
{
foreach (var item in source)
{
yield return count;
}
}
}
Note that in both cases, the sequence would be re-evaluated on each "repeat" - so it could potentially give different results, even a different length... Indeed, some sequences can't be evaluated more than than once. You need to be careful about what you do this with, basically:
ToList()
first and call Repeat
on thatRepeat
as aboveSee more on this question at Stackoverflow