How can I list an enumeration?

I need an elegant method that will enumerate and enumerate each of the same number of elements in it, except the last:

public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, Int32 chunkSize) { // TODO: code that chunks } 

Here is what I tried:

  public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, Int32 chunkSize) { var count = values.Count(); var numberOfFullChunks = count / chunkSize; var lastChunkSize = count % chunkSize; for (var chunkIndex = 0; chunkSize < numberOfFullChunks; chunkSize++) { yield return values.Skip(chunkSize * chunkIndex).Take(chunkSize); } if (lastChunkSize > 0) { yield return values.Skip(chunkSize * count).Take(lastChunkSize); } } 

UPDATE A similar topic about list splitting has just been discovered. Splitting a list in sublists with LINQ .

+7
source share
3 answers

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()); } } 
+11
source
 public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize) { while (source.Any()) { yield return source.Take(chunksize); source = source.Skip(chunksize); } } 
+4
source

There was only quick testing, but it seems to work:

 public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, Int32 chunkSize) { var valuesList = values.ToList(); var count = valuesList.Count(); for (var i = 0; i < (count / chunkSize) + (count % chunkSize == 0 ? 0 : 1); i++) { yield return valuesList.Skip(i * chunkSize).Take(chunkSize); } } 
+1
source

All Articles