ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Cycle

Repeats a sequence forever.

Source

public static IEnumerable<T> Cycle<T>(this IEnumerable<T> source)
{
    while (true)
    {
        foreach (var item in source)
        {
            yield return item;
        }
    }
}

Example

var people = new[] { "Fred", "Bill", "Susan", "Amy" };
var teamNames = new[] { "Red", "Blue" };
var assignments = people.Zip(teamNames.Cycle(), (p, t) => new { Person = p, Team = t });
var teams =
from a in assignments
group a by a.Team into ts
select new { TeamName = ts.Key, Members = from tm in ts select tm.Person };

Author: Daniel Pratt

Submitted on: 16 jun. 2010

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 4804