Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# repeating IEnumerable multiple times

Tags:

c#

ienumerable

How to repeat whole IEnumerable multiple times?

Similar to Python:

> print ['x', 'y'] * 3
['x', 'y', 'x', 'y', 'x', 'y']
like image 667
m0nhawk Avatar asked Aug 27 '26 01:08

m0nhawk


1 Answers

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 item;
        }
    }
}

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
like image 154
Jon Skeet Avatar answered Aug 29 '26 14:08

Jon Skeet