In VB.NET, a List is a dynamic collection that allows storing multiple elements of the same type. Unlike arrays, Lists can grow and shrink dynamically, making them more flexible for handling data.
Lists are part of the System.Collections.Generic namespace and provide various useful methods like Add(), Remove(), Sort(), and Contains().
In this blog, we will explore how to declare, initialize, and use Lists in VB.NET with examples.
Declaring and Initializing a List in VB.NET
To use a List in VB.NET, first import the System.Collections.Generic namespace.
🔹 Syntax:
Dim listName As New List(Of DataType)
🔹 Example: Declaring and Initializing a List
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim names As New List(Of String)() ' Creating a list of strings
names.Add("Alice")
names.Add("Bob")
names.Add("Charlie")
' Displaying the List
For Each name In names
Console.WriteLine(name)
Next
End Sub
End Module
Output:
Alice
Bob
Charlie
Common Operations on Lists
a) Adding Elements to a List
Use the .Add()
method to insert elements into a list.
Dim numbers As New List(Of Integer)()
numbers.Add(10)
numbers.Add(20)
numbers.Add(30)
b) Removing Elements from a List
Use .Remove(value)
to remove a specific element or .RemoveAt(index)
to remove an element at a specific position.
numbers.Remove(20) ' Removes value 20
numbers.RemoveAt(0) ' Removes the first element
c) Checking If an Item Exists
Use .Contains(value)
to check if an item exists in the list.
If numbers.Contains(30) Then
Console.WriteLine("30 is in the list")
End If
d) Sorting a List
Use .Sort()
to sort elements in ascending order.
numbers.Sort()
e) Getting the Count of Items
Use .Count
to get the total number of elements in a list.
Console.WriteLine("Total elements: " & numbers.Count)
Conclusion
Lists in VB.NET provide a flexible and powerful way to handle collections of data. With built-in methods like Add, Remove, Sort, and Contains, Lists offer an efficient way to manage dynamic data structures.
🚀 Start using Lists in VB.NET today to simplify your programming tasks!