How to split a list into sublists (list of lists) by checking a condition on elements in VB.NET

1 Answer

0 votes
Imports System
Imports System.Linq
Imports System.Collections.Generic
				
Public Module Module1
	Public Sub Main()
		  	Dim lst As List(Of Integer) = New List(Of Integer)() From {1, 2, 3, 0, 4, 5, 
			                                                           6, 7, 0, 8, 9, 10}
        	
			Dim list_of_lists_by_zero = lst.Aggregate(New List(Of List(Of Integer)) From {
            							New List(Of Integer)()
        							}, Function(list, value)
               								list.Last().Add(value)
               								If value = 0 Then list.Add(New List(Of Integer)())
               								Return list
           								End Function)

        	For Each subList As List(Of Integer) In list_of_lists_by_zero
            	For Each elements As Integer In subList
                	Console.WriteLine(elements)
            	Next
            	Console.WriteLine()
        	Next
	End Sub
End Module




' run:
'
' 1
' 2
' 3
' 0
' 
' 4
' 5
' 6
' 7
' 0
'
' 8
' 9
' 10
' 

 



answered Mar 10, 2021 by avibootz
...