Visual Basic .NET - List

VB.NET List is a generic collection class in the .NET framework that is used to store a sequence of elements of the same data type. It is a dynamic collection class that provides the ability to add, remove, and modify elements at runtime. The List class is part of the System.Collections.Generic namespace and is commonly used in various applications.

Declaring a List in VB.NET:

Dim mylist As New List(Of String)

Adding Elements to a List:

mylist.Add("Apple")
mylist.Add("Banana")
mylist.Add("Cherry")

Removing Elements from a List:

mylist.Remove("Banana")

Accessing Elements in a List:

Console.WriteLine(mylist(0))

Iterating Over a List:

For Each element As String In mylist
    Console.WriteLine(element)
Next

Sorting a List:

mylist.Sort()

Methods:

  • Count property: returns the number of elements in the list.
  • Clear method: removes all elements from the list.
  • Contains method: checks whether an element exists in the list.
  • IndexOf method: returns the index of the first occurrence of a specified element.
  • Insert method: inserts an element at a specified index.
  • RemoveAt method: removes an element at a specified index.

Adding and removing elements:

Dim myList As New List(Of String)
myList.Add("apple")
myList.Add("banana")
myList.Add("cherry")
myList.Remove("banana")

Iterating through a list:

Dim myList As New List(Of String)
myList.Add("apple")
myList.Add("banana")
myList.Add("cherry")
For Each item As String In myList
    Console.WriteLine(item)
Next

Sorting a list:

Dim myList As New List(Of String)
myList.Add("apple")
myList.Add("banana")
myList.Add("cherry")
myList.Sort()

Searching for an element in a list:

Dim myList As New List(Of String)
myList.Add("apple")
myList.Add("banana")
myList.Add("cherry")
Dim index As Integer = myList.IndexOf("banana")

Checking if a list contains an element:

Dim myList As New List(Of String)
myList.Add("apple")
myList.Add("banana")
myList.Add("cherry")
Dim contains As Boolean = myList.Contains("banana")