Sometimes you need to handle data in batches. With help of this extension method, all collections derived from an
IEnumerable are easy to populate in batches. Note that this code needs to be placed in a static class, so in terms of VB.NET in a module.
Imports System.Runtime.CompilerServices Public Module EnumerableExtensions [Extension] Public Iterator Function InBatches(Of T)(source As IEnumerable(Of T), size As Integer) As IEnumerable(Of IEnumerable(Of T)) Dim start As Integer = 0 While start < source.Count() Yield source.Skip(start).Take(size) start += size End While End Function End Module
If you take a closer look at the code you can see that you can provide a batch size. The method returns an
IEnumerable(Of IEnumerable(Of)). It uses the LINQ extension methods
Take(). Quite simple. Beside of these extension methods, it uses also Iterators, so the consuming method can populate the result already in the first
For.. Each. Consuming this method is even more simple. Assume that we have a collection of numbers. In this example simple created by the function
GetNumbers(). But this could be every ‘list’ of objects. A list with Customers or all return values of a LINQ query.
Private Function GetNumbers() As List(Of Integer) Dim numbers As New List(Of Integer) For counter = 1 To 27 numbers.Add(counter) Next Return numbers End Function
Simply call the
InBatches() extension method and loop trough all returned batches.
' Get the list of numbers in batches of 5 Dim numbersInBatches = GetNumbers().InBatches(5) ' Loop trough the batches For Each numbersInBatch In numbersInBatches ' Loop trough all elements in the batch For Each number In numbersInBatch Debug.Write(number.ToString() & "-") Next Debug.WriteLine("") Next
This will be result in six batches. Five batches with five elements and and the last batch with the two elements left.