Mega Code Archive

 
Categories / C# / Collections Data Structure
 

Creates a list by repeating another list

using System.Linq; using System.Diagnostics; namespace System.Collections.Generic {     public static class EnumeratorExtensions     {         /// <summary>         /// Creates a list by repeating another list.         /// </summary>         /// <typeparam name="T"></typeparam>         /// <param name="source">The list to repeat.</param>         /// <param name="count">The number of items to return.</param>         /// <returns>A circular list of items.</returns>         public static IEnumerable<T> Cycle<T>(this IEnumerable<T> source, int count)         {             if (source == null)                 throw new ArgumentNullException("source");             return CycleIterator<T>(source, count);         }         private static IEnumerable<T> CycleIterator<T>(IEnumerable<T> source, int count)         {             Debug.Assert(source != null, "source is null.");             int i = 0;             while (i < count)                 using (IEnumerator<T> data = source.GetEnumerator())                 {                     while (i < count && data.MoveNext())                     {                         yield return data.Current;                         i++;                     }                 }         }     } }