HomeSearch

VB.NET List Examples

Use the List type: add, remove and get elements from Lists. Lists resize when space is needed.

List.

This collection is a resizable array. It stores a variable number of elements in an expandable collection. Unlike an array, it changes its size as needed, on its own.

Type.

The List type offers many useful methods. We add elements. We count elements. We can locate elements with IndexOf or Find. With special syntax we initialize lists.Initialize List

First example.

Here we create 2 Lists with different syntax forms. Each list has 4 elements—4 Integers of the values 2, 3, 5 and 7. We access Count, and the Add() subroutine.

Of Integer: The keywords "Of Integer" mean that the List will contain only Integers. Other types, even Objects, are not allowed in it.

Add: The argument to the Add subroutine is the value we want to add to the List. The value is added after all existing elements.

Version 1: We call Add 4 times to add the 4 Integers. We access Count, and get the last element (which is 7) by subtracting 1 from Count.

Version 2: This code does the same thing as version 1, but it uses a shorter syntax form—the List initializer—to create the list.

VB.NET program that uses Add, Count, initializer Module Module1 Sub Main() ' Version 1: create list of 4 Integers with Add. Dim list As New List(Of Integer) list.Add(2) list.Add(3) list.Add(5) list.Add(7) Console.WriteLine("LIST 1 COUNT: {0}", list.Count) Console.WriteLine("LIST 1 LAST: {0}", list(list.Count - 1)) ' Version 2: create list with initializer. Dim list2 As New List(Of Integer)({2, 3, 5, 7}) Console.WriteLine("LIST 2 COUNT: {0}", list2.Count) Console.WriteLine("LIST 2 LAST: {0}", list2(list2.Count - 1)) End Sub End Module Output LIST 1 COUNT: 4 LIST 1 LAST: 7 LIST 2 COUNT: 4 LIST 2 LAST: 7

Loops.

We can loop over the elements in a List instance. The program adds three integers to the List contents, and then uses a For-Each loop construct. Finally it uses a For-loop.

Note: The expression "list.Count - 1" is used for the upper loop bounds on the For-loop. This keeps the index valid throughout.

Function: In the second loop, the Item function is invoked. This is an indexer function—it allows you to access an element at that index.

VB.NET program that uses For-Each and For, List Module Module1 Sub Main() Dim list As New List(Of Integer) list.Add(2) list.Add(3) list.Add(7) ' Loop through list elements. Dim num As Integer For Each num In list Console.WriteLine(num) Next ' Loop through list with a for-to loop. Dim i As Integer For i = 0 To list.Count - 1 Console.WriteLine(list.Item(i)) Next i End Sub End Module Output 2 3 7 2 3 7

Count, Clear.

The Count property returns the total number of elements in the List. The Clear function removes all the elements so that the next invocation of Count will return zero.

Here: We use the Count property and the Clear function on the List type instance.

VB.NET program that uses Count and Clear Module Module1 Sub Main() ' Create a list of booleans. Dim list As New List(Of Boolean) list.Add(True) list.Add(False) list.Add(True) ' Write the count. Console.WriteLine(list.Count) ' Clear the list elements. list.Clear() ' Write the count again. Console.WriteLine(list.Count) End Sub End Module Output 3 0

Initialize.

Let us initialize a List. The benefit to using this syntax is that it reduces the size of your source text. It sometimes increases readability because of that.Initialize List

Note: There is no important difference at the level of the intermediate language of the compiled program.

VB.NET program that initializes List instance Module Module1 Sub Main() ' Create a list of three integers. Dim list As New List(Of Integer)(New Integer() {2, 3, 5}) ' Write the count. Console.WriteLine(list.Count) End Sub End Module Output 3

If-statement.

We often need to scan or loop through the elements in the List and use logical tests on them. Perhaps we need to test each element against a specific value.

Tip: To do this, you can use a For-Each loop and then an enclosed If-statement in the VB.NET language.

VB.NET program that uses if, List elements Module Module1 Sub Main() ' Create a list of three integers. Dim list As New List(Of Integer)(New Integer() {2, 3, 5}) ' Loop through each number in the list. ' ... Then check it against the integer 3. Dim num As Integer For Each num In list If (num = 3) Then Console.WriteLine("Contains 3") End If Next End Sub End Module Output Contains 3

Join.

The String.Join method combines an array of strings into a single string with a specific delimiter character dividing the parts. A List can now be used with Join.

Note: The .NET 4.0 Framework provides a new String.Join overload that accepts an argument of type IEnumerable.

Join

Here: We convert a List into an array. We apply the ToArray extension and then pass as an argument this result to String.Join.

ToArray
VB.NET program that uses Join, List Module Module1 Sub Main() ' Create a list of strings. ' ... Then use the String.Join method on it. Dim list As New List(Of String) list.Add("New York") list.Add("Mumbai") list.Add("Berlin") list.Add("Istanbul") Console.WriteLine(String.Join(",", list.ToArray)) End Sub End Module Output New York,Mumbai,Berlin,Istanbul

List, keys.

List and Dictionary can be used together. We can acquire a List instance of all of the keys from a Dictionary instance. Then, that List can be used just like any other List.

Dictionary: More information is available on the Dictionary generic type in the VB.NET language.

Dictionary
VB.NET program that uses Keys and List Module Module1 Sub Main() ' Create a dictionary of integers and boolean values. ' ... Add two pairs to it. Dim dictionary As New Dictionary(Of Integer, Boolean) dictionary.Add(3, True) dictionary.Add(5, False) ' Get the list of keys. Dim list As New List(Of Integer)(dictionary.Keys) ' Loop through the list and display the keys. Dim num As Integer For Each num In list Console.WriteLine(num) Next End Sub End Module Output 3 5

Insert.

When we use Insert, the first argument must be the desired index for the element. The second argument is the element to insert.

Index: For example, the index 1 will put the element in the second index, because the List is ordered starting at zero.

VB.NET program that uses Insert method Module Module1 Sub Main() ' Create a list of strings. Dim list As New List(Of String) list.Add("spaniel") list.Add("beagle") ' Insert a pair into the list. list.Insert(1, "dalmatian") ' Loop through the entire list. Dim str As String For Each str In list Console.WriteLine(str) Next End Sub End Module Output spaniel dalmatian beagle

AddRange, InsertRange.

Suppose we want to append or insert an array of Integers into a List of Integers. We can use the AddRange or InsertRange Subs.

Tip: The type of the array we insert (like Integer or String) must match the target List's element type.

Arrays

Tip 2: We can insert one List into another with AddRange and InsertRange—the syntax is the same (just pass a list instead of an array).

VB.NET program that uses AddRange, InsertRange Module Module1 Sub Main() ' Initial list. Dim list As List(Of Integer) = New List(Of Integer)({1, 2}) ' Add ints on the end. list.AddRange(New Integer() {3, 4}) ' Insert ints at the start. list.InsertRange(0, New Integer() {-2, -1}) ' Display final list. For Each value In list Console.WriteLine("FINAL LIST: {0}", value) Next End Sub End Module Output FINAL LIST: -2 FINAL LIST: -1 FINAL LIST: 1 FINAL LIST: 2 FINAL LIST: 3 FINAL LIST: 4

GetRange.

This function receives 2 arguments. The first is the starting index. And the second argument is the number of elements (count) you wish to receive.
VB.NET program that uses GetRange method Module Module1 Sub Main() ' Create a new list of strings and add five strings to it. Dim list As New List(Of String)(New String() {"nile", _ "amazon", _ "yangtze", _ "mississippi", _ "yellow"}) ' Loop through the strings. Dim str As String For Each str In list.GetRange(1, 2) Console.WriteLine(str) Next End Sub End Module Output amazon yangtze

IndexOf.

This method locates a value within a List. It returns the index of a match was found. It returns -1 if no matching value exists in the List.
VB.NET program that uses IndexOf Module Module1 Sub Main() Dim sizes As List(Of Integer) = New List(Of Integer) sizes.Add(10) sizes.Add(20) sizes.Add(30) ' The value 20 occurs at the index 1. Dim index20 As Integer = sizes.IndexOf(20) Console.WriteLine(index20) ' The value 100 does not occur, so IndexOf returns -1. Dim index100 As Integer = sizes.IndexOf(100) If index100 = -1 Then Console.WriteLine("Not found") End If End Sub End Module Output 1 Not found

IEnumerable.

The List (like an array) can be used as an IEnumerable type—we can pass List to methods where an IEnumerable is required. We can then loop over (with For Each) the collection.

Here: We create a List and an array in Main. We pass those of those to the PrintElements Sub—it handles all IEnumerable types.

Tip: Often we can use IEnumerable-receiving functions to share code that must act upon Lists and arrays.

IEnumerable
VB.NET program that uses List with IEnumerable Interface Module Module1 Sub Main() ' Create List and pass it as an IEnumerable. Dim list As List(Of Integer) = New List(Of Integer)({10, 20, 30}) PrintElements(list) ' Use array as an IEnumerable. Dim array As Integer() = {100, 200, 300} PrintElements(array) End Sub Sub PrintElements(ByVal elements As IEnumerable(Of Integer)) ' Handle elements in IEnumerable. For Each element In elements Console.WriteLine("Element: {0}", element) Next End Sub End Module Output Element: 10 Element: 20 Element: 30 Element: 100 Element: 200 Element: 300

Find.

We can also use the Find, FindIndex, FindLast and FindLastIndex functions. These provide a way for us to declaratively search a List. This reduces complexity.List Find

BinarySearch.

In a binary search, a value is located in a sorted list by testing positions in the list. The search then "hones" in on the value. This can optimize performance.BinarySearch List

Duplicates.

Unlike a Dictionary, a List can contain duplicate elements. This often can be a problem. We can remove these duplicates in many ways.Remove Duplicates

Convert.

Often we must use custom methods to convert and modify List collections. We can convert a List into another type, like a Dictionary.Convert Dictionary, List

Notes, Dictionary.

If we have a List that we repeatedly search for a certain value, using a Dictionary may be faster. The hashing in a Dictionary can speed up access to keys.Dictionary

Tip: Knowing the difference between List and Dictionary is important skill for VB.NET developers—this will help many real-world programs.

A summary.

The List type is a generic, constructed type. It has some performance advantages over other structures. In many programs, the List type is useful.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.