Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, Int32 chunkSize)
- {
- // TODO: code that chunks
- }
- 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);
- }
- }
- 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 => x.v));
- }
- }
- 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());
- }
- }
- 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement