Home
VB.NET
List Nested Example
This page was last reviewed on Jan 12, 2024.
Dot Net Perls
List, nested. While 2D arrays are possible in VB.NET programs, nested Lists are often a more convenient choice. They can expand and resize themselves more easily.
List
2D Array
Shows a list
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.
Example. 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.
Part 1 In the Main subroutine we set up our nested List. Please note the declaration syntax—we must use 2 "Of" keywords.
Random
Part 2 We use a For-Each loop to iterate over the top-level List and then, in a separate loop, iterate its sub-lists.
For
Part 3 We can access a single element with 2 indexing expressions. This can an exception if the element is out-of-range.
Part 4 To determine the total count of all elements, we must sum up the Counts of the sub-lists.
Shows a list
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 Module
Elements: 2 2 2 4 2 4 3 Element at 1, 0: 2 Count: 7
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 12, 2024 (image).
Home
Changes
© 2007-2024 Sam Allen.