.NET – Break up a list into parts

I needed to break up a list into equal parts today, and I found that the code did not exist out there to create chunks to process as a batch. Specifically, i was working on sending emails to a large number of recipients. I created a List(Of T) extension method to break the addresses into groups:

Also, this code highlighter strips out the declaration.

Public Module ListHelpers

    
    Public Function Chunk(Of T)(theList As List(Of T), chunkSize As Integer) As List(Of List(Of T))
        Dim output As List(Of List(Of T)) = New List(Of List(Of T))()
        Dim bottom As Integer = 0
        Dim thisChunkSize As Integer
        While bottom < theList.Count - 1
            thisChunkSize = chunkSize
            If (bottom + chunkSize) > theList.Count - 1 Then
                thisChunkSize = theList.Count - 1 - bottom
            End If
            output.Add(New List(Of T)(theList.GetRange(bottom, thisChunkSize)))
            bottom = bottom + chunkSize
        End While
        Return output
    End Function

End Module
Posted Tuesday, March 29th, 2011 under Code.

Leave a Reply