Loop
Here's a kinda cool one I just thought of. (If I just thought of it, maybe it's not that useful? But I thought of it because I have a use for it.) Loop through a sequence repeatedly to generate an infinite sequence. This accomplishes something kind of like what Enumerable.Range and Enumerable.Repeat give you, except it can be used for an arbitrary (unlike Range) sequence (unlike Repeat):
public static IEnumerable<T> Loop<T>(this IEnumerable<T> source)
{
while (true)
{
foreach (T item in source)
{
yield return item;
}
}
}
Usage:
var numbers = new[] { 1, 2, 3 };
var looped = numbers.Loop();
foreach (int x in looped.Take(10))
{
Console.WriteLine(x);
}
Output:
1
2
3
1
2
3
1
2
3
1
Note: I suppose you could also accomplish this with something like:
var looped = Enumerable.Repeat(numbers, int.MaxValue).SelectMany(seq => seq);
...but I think Loop is clearer.