Find An Item In List Using VB.NET
In this article I explain how to find specified item from list using vb.net.
Find an Item
The Contains method checks if the specified item is already exists in the List. The following code snippet checks if an item is already exits.
If DepartmentList.Contains("Service") Then
Console.WriteLine("Department found!")
End If
The IndexOf method returns the first index of an item if found in the List.
Dim idx As Integer = DepartmentList.IndexOf("Testing")
The LastIndexOf method returns the last index of an item if found in the List.
idx = DepartmentList.LastIndexOf("Service")
The following code snippet shows how to use the Contains, the IndexOf and the LastIndexOf methods.
Imports System.Text
Imports System.IO
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim DepartmentList As New List(Of String)()
DepartmentList.Add("Service")
DepartmentList.Add("Finance")
DepartmentList.Add("Maintenance")
DepartmentList.Add("Testing")
DepartmentList.Add("HR")
DepartmentList.Add("Service")
' Contains - Check if an item is in the list
If DepartmentList.Contains("Service") Then
Console.WriteLine()
Console.WriteLine("Department found!")
End If
' Find an item and replace it with new item
Dim idx As Integer = DepartmentList.IndexOf("Testing")
If idx >= 0 Then
DepartmentList(idx) = "New Department"
End If
Console.WriteLine()
Console.WriteLine(vbLf & "IndexOf ")
For Each department In DepartmentList
Console.WriteLine(department)
Next
' Find Last index of
idx = DepartmentList.LastIndexOf("Service")
If idx >= 0 Then
DepartmentList(idx) = "New Service"
End If
Console.WriteLine()
Console.WriteLine()
Console.WriteLine(vbLf & "LastIndexOf ")
For Each Department In DepartmentList
Console.WriteLine()
Console.WriteLine(Department)
Next
Console.ReadLine()
End Sub
End Module
Output: