List
, nestedWhile 2D arrays are possible in VB.NET programs, nested Lists are often a more convenient choice. They can expand and resize themselves more easily.
By creating a List
of Lists, we can use each List
an independent row. The syntax for creating nested Lists can be cumbersome—the types must be specified all at once.
This program contains 2 subroutines—the Main
sub sets up and populates the nested List
. And the Display subroutine loops over the List
we created, and prints its elements.
Main
subroutine we set up our nested List
. Please note the declaration syntax—we must use 2 "Of" keywords.For-Each
loop to iterate over the top-level List
and then, in a separate loop, iterate its sub-lists.Module Module1 Sub Main() ' Part 1: Create a List and place sublists within it with Add. Dim list = New List(Of List(Of Integer)) Dim rand = New Random() For i = 0 To 2 ' Create a row with a random number of integers. Dim sublist = New List(Of Integer) Dim top = rand.Next(1, 4) For v = 0 to top - 1 sublist.Add(rand.Next(1, 5)) Next list.Add(sublist) Next ' Call the Display sub. Display(list) End Sub Sub Display(list As List(Of List (Of Integer))) ' Part 2: display elements in the List. Console.WriteLine("Elements:") For Each sublist in list For Each value in sublist Console.Write(value) Console.Write(" ") Next Console.WriteLine() Next ' Part 3: display a single element. Console.WriteLine("Element at 1, 0:") Console.WriteLine(list(1)(0)) ' Part 4: write list count. Dim count = 0 For Each sublist in list count += sublist.Count Next Console.WriteLine("Count:") Console.WriteLine(count) End Sub End ModuleElements: 2 2 2 4 2 4 3 Element at 1, 0: 2 Count: 7
In a sense, there is no such thing as a 2D List
in .NET—we just have a List
, and we can place separate Lists within it. But as a real-world solution, nested Lists are worth considering.