How to split a list into evenly sized chunks in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class SplitListIntoChunks_VB_NET
    Public Shared Sub Main()
        Dim aList = New List(Of Integer)()

        For i As Integer = 0 To 31 - 1
            aList.Add(i)
        Next

        Dim result = Split(aList, 4)

        For Each chunk In result
            Console.WriteLine(String.Join(", ", chunk))
        Next
    End Sub

	Public Shared Iterator Function Split(Of T)(ByVal theList As List(Of T), ByVal chunk As Integer) As IEnumerable(Of List(Of T))
        Dim i As Integer = 0

        ' yield - provide the next value in iteration
		While i < theList.Count
            Yield theList.GetRange(i, Math.Min(chunk, theList.Count - i))
            i += chunk
        End While
    End Function
End Class

 
 
' run:
' 
' 0, 1, 2, 3
' 4, 5, 6, 7
' 8, 9, 10, 11
' 12, 13, 14, 15
' 16, 17, 18, 19
' 20, 21, 22, 23
' 24, 25, 26, 27
' 28, 29, 30
'

 



answered Nov 12, 2024 by avibootz

Related questions

1 answer 118 views
9 answers 872 views
1 answer 116 views
2 answers 153 views
1 answer 120 views
1 answer 126 views
...