If memory consumption is not a concern, then something like this?
static class Ex { public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>( this IEnumerable<TValue> values, Int32 chunkSize) { return values .Select((v, i) => new {v, groupIndex = i / chunkSize}) .GroupBy(x => x.groupIndex) .Select(g => g.Select(x => xv)); } }
Otherwise, you can get an ad with the yield keyword, for example:
static class Ex { public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>( this IEnumerable<TValue> values, Int32 chunkSize) { using(var enumerator = values.GetEnumerator()) { while(enumerator.MoveNext()) { yield return GetChunk(enumerator, chunkSize).ToList(); } } } private static IEnumerable<T> GetChunk<T>( IEnumerator<T> enumerator, int chunkSize) { do{ yield return enumerator.Current; }while(--chunkSize > 0 && enumerator.MoveNext()); } }
spender
source share