Visual Basic List

In visual basic, List is a generic type of collection so it will allow storing only strongly typed objects i.e. elements of same data type and the size of list will vary dynamically based on our application requirements like adding or removing elements from the list.

 

In visual basic, the list is same as an arraylist but the only difference is arraylist is a non-generic type of collection. So, it will allow storing elements of different data types.

Visual Basic List Declaration

In visual basic, list is a generic type of collection and it is provided by System.Collections.Generic namespace.

 

As discussed, the collection is a class so to define a list, we must need to declare an instance of the list class before we perform any operations like add, delete, etc. like as shown below.

 

Dim lst As List(Of T) = New List(Of T)()

If you observe the above list declaration, we created a generic list (lst) with an instance of List class using type parameter (T) as a placeholder with brackets (Of type).

 

Here, the bracketed item (Of T) will indicate that the list is a generic type and type parameter (T) is used to represent a type of elements to be accepted by list.

 

In visual basic, the generic list (List(Of T)) is an implementation of IList(Of T) interface so we can also use IList(Of T) interface to create an object of the generic list (List(Of T)) like as shown below.

 

Dim lst As IList(Of T) = New List(Of T)()

Visual Basic List Initialization

Following is the example of initializing a generic list by specifying the required type to accept values to store.

 

Dim lst As List(Of String) = New List(Of String)()

If you observe the above example, we defined a list (lst) with String data type to store only string elements.

Visual Basic List Properties

Following are the some of commonly used properties of generic list in visual basic programming language.

 

PropertyDescription
Capacity It is used to get or set the number of elements a list can contain.
Count It is used to get the number of elements in list.
Item It is used get or set an element at the specified index.

Visual Basic List Methods

Following are the some of commonly used methods of generic list to perform add, search, insert, delete or sort operations in visual basic programming language.

 

MethodDescription
Add It is used to add an element at the end of the List.
AddRange It is used to add all the elements of specified collection at the end of the List.
Clear It will remove all the elements from the List.
Contains It is used determine whether the specified element exists in the List or not.
CopyTo It is used to copy entire List to compatiable one-dimensional array.
Find It is used to search for an element that matches the conditions defined by the specified predicate and return the first occurrence of the List.
FindAll It is used to retrieve all the elements that matches the conditions defined by the specified predicate.
ForEach It is used to iterate through the List to access an elements.
Insert It is used to insert an element into the List at the specified index.
InsertRange It is used to insert all the elements of specified collection into List starting from the specified index.
Remove It is used to remove the first occurence of specified element from the List.
RemoveAt It is used to remove an element from the List based on the specified index position.
RemoveRange It is used to remove a range of elements from the List.
Reverse It reverse the order of List elements.
Sort It sorts the elements in the List.
ToArray It will copies the elements of List to new array object.

Visual Basic Generic List (List(Of T)) Example

Following is the example of using the generic list (List(Of T)) in visual basic programming language.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Creating and initializing list

        Dim lst As List(Of Integer) = New List(Of Integer)()

        lst.Add(1)

        lst.Add(8)

        lst.Add(45)

        Dim lst2 As List(Of String) = New List(Of String)()

        lst2.Add("Hi")

        lst2.Add("Welcome")

        lst2.Add("to")

        lst2.Add("Tutlane")

        Console.WriteLine("List1 Elements Count: " & lst.Count)

        Console.WriteLine("List1 Capacity: " & lst.Capacity)

        Console.WriteLine("*********List1 Elements********")

        ' Accessing list elements

        For Each item In lst

            Console.WriteLine(item)

        Next

        Console.WriteLine("List2 Elements Count: " & lst2.Count)

        Console.WriteLine("List2 Capacity: " & lst2.Capacity)

        Console.WriteLine("*********List2 Elements********")

        For Each item In lst2

            Console.WriteLine(item)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe above example, we are able to define a new generic lists (lst, lst2) collection. Here, we added only the defined data type (IntegerString) values to the newly created lists (lst, lst2) by using Add method and accessing the generic list (lst, lst2) elements by using For Each loop.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Generic List Example Result

 

This is how we can use the generic list in visual basic to store the group of defined type elements based on our requirements.

 

Following are the some of useful examples to work with generic list in visual basic programming language.

Visual Basic Add Elements to List

In visual basic, we can add elements to the list either by using Add / AddRange methods or at the time of initialization based on our requirements.

 

Following is the example of adding elements to the list using Add or AddRange methods in visual basic.

 

Module Module1

    Public Class User

        Public Property Id As Integer

        Public Property Name As String

        Public Property Location As String

    End Class

    Sub Main(ByVal args As String())

        ' Creating and initializing list

        Dim lst As List(Of Integer) = New List(Of Integer)() From {1, 8, 45, 70}

        Console.WriteLine("List1 Elements Count: " & lst.Count)

        Console.WriteLine("*********List1 Elements********")

        ' Accessing list elements

        For Each item In lst

            Console.WriteLine(item)

        Next

        ' AddRange method

        Dim lst2 As List(Of Integer) = New List(Of Integer)()

        lst2.AddRange(lst)

        Console.WriteLine("List2 Elements Count: " & lst2.Count)

        Console.WriteLine("*********List2 Elements********")

        For Each item In lst2

            Console.WriteLine(item)

        Next

        Dim users As List(Of User) = New List(Of User)() From {

            New User With {

                .Id = 1,

                .Name = "Suresh Dasari",

                .Location = "Hyderabad"

            },

            New User With {

                .Id = 2,

                .Name = "Rohini Alavala",

                .Location = "Guntur"

            }

        }

        users.Add(New User With {

            .Id = 3,

            .Name = "Trishika Dasari",

        .Location = "Guntur"

        })

        users.Add(New User With {

            .Id = 4,

            .Name = "Praveen Alavala",

            .Location = "Eluru"

        })

        Console.WriteLine("List3 Elements Count: " & users.Count)

        Console.WriteLine("*********List3 Elements********")

        For Each u As User In users

            Console.WriteLine("Id:{0}, Name:{1}, Location:{2}", u.Id, u.Name, u.Location)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we created multiple lists (lst, lst2, users) and adding elements to the lists in different ways like added some of the elements during the initialization time and some other elements by using Add & AddRange methods.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Add Elements to List Example Result

Visual Basic Access List Elements

In visual basic, we have a different ways to access list elements i.e. either by using index positions or by iterating through the list using For / For Each loops.

 

Following is the example of accessing a list elements in different ways.

 

Module Module1

    Public Class User

        Public Property Id As Integer

        Public Property Name As String

        Public Property Location As String

    End Class

    Sub Main(ByVal args As String())

        ' Creating and initializing list

        Dim lst As List(Of Integer) = New List(Of Integer)() From {1, 8, 45, 70}

        Console.WriteLine("*********Access Elements with Index Position********")

        Console.WriteLine("Element at 0: " & lst(0))

        Console.WriteLine("Element at 2: " & lst(2))

        ' Creating List

        Dim users As List(Of User) = New List(Of User)() From {

                New User With {

                    .Id = 1,

                    .Name = "Suresh Dasari",

                    .Location = "Hyderabad"

                },

                New User With {

                    .Id = 2,

                    .Name = "Rohini Alavala",

                    .Location = "Guntur"

                },

                New User With {

                    .Id = 3,

                    .Name = "Trishika Dasari",

                    .Location = "Guntur"

                },

                New User With {

                    .Id = 4,

                    .Name = "Praveen Alavala",

                    .Location = "Eluru"

                }

            }

        Console.WriteLine("*********Access Elements with For Loop********")

        ' For loop to access list elements

        For i As Integer = 0 To users.Count - 1

            Console.WriteLine("Id:{0}, Name:{1}, Location:{2}", users(i).Id, users(i).Name, users(i).Location)

        Next

        Console.WriteLine("*********Access Elements with Foreach Loop********")

        ' For Each loop to access list elements

        For Each u As User In users

            Console.WriteLine("Id:{0}, Name:{1}, Location:{2}", u.Id, u.Name, u.Location)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we are accessing generic list elements in different ways by using index positions, For and For Each loops based on our requirements.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Access List Elements Example Result

Visual Basic Insert Elements into List

In visual basic, we can insert elements into the list either by using Insert() or InsertRange() methods.

 

Following is the example of inserting elements into the list by using Insert and InsertRange methods in visual basic.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Creating and initializing list

        Dim lst As List(Of Integer) = New List(Of Integer)() From {1, 8, 45, 70}

        ' inserting elements into list

        lst.Insert(0, 10)

        lst.Insert(3, 50)

        Dim lst2 As List(Of Integer) = New List(Of Integer)() From {200, 300}

        ' inserting lst2 into lst at position 2

        lst.InsertRange(2, lst2)

        Console.WriteLine("*********ArrayList Elements********")

        For Each item In lst

            Console.WriteLine(item)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we inserted elements into the list at different index positions (0, 3) by using Insert() method. Same way, by using InsertRange() method we are inserting all the element of newly created list (lst2) into lst at index position 2.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Insert Elements into List Example Result

Visual Basic Remove Elements from List

In visual basic, we have different methods to remove elements from the list i.e. either by using Remove() or RemoveAt() or RemoveRange() methods.

 

Following is the example of deleting elements from the list in visual basic programming language.

 

ModuleModule1

    Sub Main(ByVal args As String())

        ' Creating and initializing list

        Dim lst As List(Of Integer) = New List(Of Integer)() From {10, 20, 30, 40, 50, 60, 70, 80}

        ' Removing an element which is having a value 50

        lst.Remove(50)

        ' Removing an element at index 2

        lst.RemoveAt(2)

        ' Removing 2 elements starting from index 3

        lst.RemoveRange(3, 2)

        Console.WriteLine("*********List Elements********")

        For Each item In lst

            Console.WriteLine(item)

        Next

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used Remove() method to delete the particular value of the element from the list and another method RemoveAt() is used to delete an element at the specified index position.

 

Same way, we used RemoveRange() method to delete the specified number of elements from the list starting from the specified index position.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic Remove Elements from List Example Result

 

In case, if you want to remove all the elements from the list, then use the Clear() method.

 

Same way, we can use different methods like Find() method to find the elements of list and Reverse() method to reverse the order of list elements, etc. based on our requirements.

Visual Basic List Check If Item Exists

 By using Contains() method, we can check whether the specified element exists in the list or not. In case, if it exists it will return True otherwise False.

 

Following is the example of using Contains() method to check for an item exists in the list or not in visual basic.

 

Module Module1

    Sub Main(ByVal args As String())

        ' Creating and initializing list

        Dim lst As List(Of Integer) = New List(Of Integer)() From {10, 20, 30, 40, 50, 60, 70, 80}

        ' Check for an item 50 exists in list or not

        Console.WriteLine("Item Exists: " & lst.Contains(50))

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used Contains() method to check for an item (50) exists in the list (lst) or not.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Item Exists: True

Visual Basic List (List(Of T)) Overview

Following are the important points which need to remember about the list in visual basic.

 

  • The List is useful to store elements of same data type and the size of the list can grow or shrink dynamically by adding or removing elements.
  • List is a generic type of collection and available with System.Collections.Generic namespace.
  • We can access the list elements either by using loops (For and For Each) or with particular index position.
  • List(Of T) can be assigned to IList(Of T) or List(Of T) type of the variable and we can store multiple null and duplicate values in the list based on our requirement.
  • List provided different methods to perform multiple operations like add, insert, delete, sort, reverse, etc. on elements of arraylist.

Topics Covered