Can't you use Repeat
+ SelectMany
?
var take100ABC = Enumerable.Repeat(new[] { "A", "B", "C" }, 100)
.SelectMany(col => col);
In my opinion an extension method is useful only if you need it often. I doubt that you need a RepeatIndefinitely
often. But a RepeatWhile
could be handy in many cases. You could it also for an infinite repetition.
So here is my my first attempt:
public static IEnumerable<TSource> RepeatWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
TSource item = default(TSource);
do
{
foreach (TSource current in source)
{
item = current;
yield return item;
}
}
while (predicate(item));
yield break;
}
You can use it for your "infinite" repetion for example in this way:
string[] collection = { "A", "B", "C"};
var infiniteCollection = collection.RepeatWhile(s => s == s);
List<string> take1000OfInfinite = infiniteCollection.Take(1000).ToList();