Skip to content

Commit 5f62fbd

Browse files
committed
Added Chunk collection extension method & docs
1 parent d92c756 commit 5f62fbd

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

docs/articles/features/collections.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,22 @@ private void VerifyString(string val)
139139
// Do verification
140140
}
141141
```
142+
143+
## Breaking collections up into chunks using the Chunk extension
144+
145+
When you want to process your data in limited sets, you need to split your collection up. The `Chunk` extension allows you to achieve this by splitting your lists up into datasets by a specified size for you.
146+
147+
Here's how you can do this in your projects.
148+
149+
```csharp
150+
public async Task ProcessMessagesAsync(IEnumerable<Message> messages, CancellationToken cancellationToken = default )
151+
{
152+
foreach ( var messageChunk in messages.Chunk( 10 ) )
153+
{
154+
foreach ( var message in messageChunk )
155+
{
156+
await this.processor.SendMessageAsync( message, cancellationToken );
157+
}
158+
}
159+
}
160+
```

src/MADE.Collections/CollectionExtensions.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,5 +227,20 @@ public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
227227
action?.Invoke(item);
228228
}
229229
}
230+
231+
/// <summary>
232+
/// Chunks a collection of items into a collection of collections grouped into the specified chunk size.
233+
/// </summary>
234+
/// <typeparam name="T">The type of item.</typeparam>
235+
/// <param name="source">The source collection to chunk.</param>
236+
/// <param name="chunkSize">The chunk size.</param>
237+
/// <returns>A collection of collections containing the chunked items.</returns>
238+
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunkSize = 25)
239+
{
240+
return source
241+
.Select((v, i) => new { Index = i, Value = v })
242+
.GroupBy(x => x.Index / chunkSize)
243+
.Select(x => x.Select(v => v.Value));
244+
}
230245
}
231246
}

0 commit comments

Comments
 (0)