C# repeating IEnumerable multiple times

How to repeat whole IEnumerable multiple times?

Similar to Python:

> print ['x', 'y'] * 3
['x', 'y', 'x', 'y', 'x', 'y']
Jon Skeet
people
quotationmark

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:

  • If you know the sequence can only be evaluated once (or you want to get consistent results from an inconsistent sequence) but you're happy to buffer the evaluation results in memory, you can call ToList() first and call Repeat on that
  • If you know the sequence can be consistently evaluated multiple times, just call Repeat as above
  • If you're in neither of the above situations, there's fundamentally no way of repeating the sequence elements multiple times

people

See more on this question at Stackoverflow