Search code examples
c#.netlinqlazy-evaluationinfinite-sequence

linq infinite list from given finite list


Given a finite list of elements, how can I create a (lazily-evaluated, thanks LINQ!) infinite list that just keeps iterating over my initial list?

If the initial list is {1, 2, 3}, I want the new list to return {1, 2, 3, 1, 2, 3, 1, ...}


Solution

  • yield return is a fairly handy operator for this, although it doesn't really require LINQ specifically.

    IEnumerable<int> GetInfiniteSeries(IEnumerable<int> items) {
        while (true) {
           foreach (var item in items) { 
               yield return item;
           }
        }
    }