Skip to content

Instantly share code, notes, and snippets.

@shamp00
Created June 2, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamp00/8541fdc394ccc23ee6c9 to your computer and use it in GitHub Desktop.
Save shamp00/8541fdc394ccc23ee6c9 to your computer and use it in GitHub Desktop.
Public NotInheritable Partial Class MoreEnumerable
Private Sub New()
End Sub
<System.Runtime.CompilerServices.Extension> _
Public Shared Function Batch(Of TSource)(source As IEnumerable(Of TSource), size As Integer) As IEnumerable(Of IEnumerable(Of TSource))
Return Batch(source, size, Function(x) x)
End Function
<System.Runtime.CompilerServices.Extension> _
Public Shared Function Batch(Of TSource, TResult)(source As IEnumerable(Of TSource), size As Integer, resultSelector As Func(Of IEnumerable(Of TSource), TResult)) As IEnumerable(Of TResult)
source.ThrowIfNull("source")
size.ThrowIfNonPositive("size")
resultSelector.ThrowIfNull("resultSelector")
Return BatchImpl(source, size, resultSelector)
End Function
<System.Runtime.CompilerServices.Extension> _
Private Shared Function BatchImpl(Of TSource, TResult)(source As IEnumerable(Of TSource), size As Integer, resultSelector As Func(Of IEnumerable(Of TSource), TResult)) As IEnumerable(Of TResult)
Debug.Assert(source IsNot Nothing)
Debug.Assert(size > 0)
Debug.Assert(resultSelector IsNot Nothing)
Dim bucket As TSource() = Nothing
Dim count = 0
For Each item As var In source
If bucket Is Nothing Then
bucket = New TSource(size - 1) {}
End If
bucket(System.Math.Max(System.Threading.Interlocked.Increment(count),count - 1)) = item
' The bucket is fully buffered before it's yielded
If count <> size Then
Continue For
End If
' Select is necessary so bucket contents are streamed too
yield Return resultSelector(bucket.[Select](Function(x) x))
bucket = Nothing
count = 0
Next
' Return the last bucket with all remaining elements
If bucket IsNot Nothing AndAlso count > 0 Then
yield Return resultSelector(bucket.Take(count))
End If
End Function
End Class
'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: @telerik
'Facebook: facebook.com/telerik
'=======================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment