Skip to content

Instantly share code, notes, and snippets.

@benjamin-bader
Created April 24, 2012 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjamin-bader/2475191 to your computer and use it in GitHub Desktop.
Save benjamin-bader/2475191 to your computer and use it in GitHub Desktop.
Cycle operator
public static IEnumerable<T> Cycle<T>(this IEnumerable<T> collection, bool forceToList = false)
{
var list = collection as IList<T>;
if (list != null)
{
return CycleList(list);
}
return forceToList
? CycleList(collection.ToList())
: CycleEnumerable(collection);
}
private static IEnumerable<T> CycleList<T>(IList<T> list)
{
var counter = 0;
var length = list.Count;
if (length == 0)
yield break;
while (true)
{
yield return list[counter];
counter = (counter + 1) % length;
}
}
private static IEnumerable<T> CycleEnumerable<T>(IEnumerable<T> collection)
{
var iter = collection.GetEnumerator();
if (!iter.MoveNext())
yield break;
while (true)
{
do
{
yield return iter.Current;
}
while (iter.MoveNext());
iter.Reset();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment