Created
April 24, 2012 01:00
-
-
Save benjamin-bader/2475191 to your computer and use it in GitHub Desktop.
Cycle operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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