Last active
December 21, 2015 11:08
-
-
Save SoulFireMage/6296647 to your computer and use it in GitHub Desktop.
Break a list(of T) into arbitrary fixed chunks - with or without Yield.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'Usage example: | |
'Dim setsOfList = OriginalList.Chunk(3) | |
'For Each innerList In setsOfList | |
'Do stuff | |
'Next | |
<Extension()> | |
Public Iterator Function ChunkData(Of TSource)(source As IEnumerable(Of TSource), chunkSize As Integer) As IEnumerable(Of IEnumerable(Of TSource)) | |
Dim _chunkSize = IIf(source.Count < chunkSize, source.Count, chunkSize) | |
Dim i = 0 | |
While i < source.Count() | |
Yield source.Skip(i).Take(_chunkSize) | |
i += _chunkSize | |
End While | |
End Function | |
<Extension()> | |
Public Function Chunk(Of T)(Source As List(Of T), chunkSize As Integer) As List(Of List(Of T)) | |
Dim _list As New List(Of List(Of T)) | |
If Source.Count < chunkSize Then chunkSize = Source.Count | |
For i = 0 To Source.Count Step chunkSize | |
Dim remainingList = Source.Skip(i + chunkSize).Count | |
If remainingList >= chunkSize Then | |
Dim innerlist = Source.GetRange(i, chunkSize).Take(chunkSize).ToList | |
_list.Add(innerlist) | |
Else | |
Dim innerlist = Source.Skip(i).Take(chunkSize).ToList | |
If innerlist.Count > 0 Then _list.Add(innerlist) | |
End If | |
Next | |
Return _list | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please note the non yield version does not take advantage of call backs, it simply provides you a list of lists, each one representing a fixed number of items from successive sections of the list.