6

How to repeat whole IEnumerable multiple times?

Similar to Python:

> print ['x', 'y'] * 3
['x', 'y', 'x', 'y', 'x', 'y']
3
  • 1
    What output do you except? Commented Feb 4, 2015 at 8:24
  • @conanak99 I have added Python output, this should be OK now. Commented Feb 4, 2015 at 8:26
  • It might be worth adding that if these were reference types (in python) then it would be the reference copied and instead of the value Commented Feb 4, 2015 at 8:36

1 Answer 1

18

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.