Generic Lists and VB.NET

Introduction

Today you will learn about Generic Lists and how to use them productively in Visual Basic. NET

Generic Lists

According to MSDN, a Generic List “represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists”. This is very vague and does not tell anyone about a Generic List’s use and advantages. Let me try to explain it better: A Generic List is simply a list that you can make yourself. This list can be anything! An example of a generic List will be a student list. Do not think of the student list containing only the student’s names, it can contain all methods and properties associated with a student object.

This means that you can create a Student class, supply some properties to it, and then make a list of Students, that will contain all the Student object’s properties and methods.

An Example

As usual, I always have an example ready. Today we will create a Generic List of Students, then delve into this Generic List’s properties and methods.

Design

Fire up Visual Studio 2012 and create a new VB.NET Windows Forms application. Once done, design your form to resemble Figure 1. This should give you a good indication of what you will be doing today.

Our Design
Figure 1Our Design

Code

Adding the Class that will be the Generic List

Add a new class to the project and name it Students. Add the following into it:

Public Class Students

	Private strStudentSurname As String
	Private strStudentName As String

	'Student Name Property
	Public Property StudentName() As String

		Get

			Return strStudentName

		End Get

		Set

			strStudentName = Value

		End Set

	End Property

	'StudentSurname Property
	Public Property StudentSurname() As String

		Get

			Return strStudentSurname

		End Get

		Set

			strStudentSurname = Value

		End Set

	End Property

	'ToString Method
	Public Overrides Function ToString() As String

		Return "Name: " & StudentName & "   Surname: " & StudentSurname

	End Function

	'Equals Method
	Public Overrides Function Equals(objTemp As Object) As Boolean

		If objTemp Is Nothing Then 	Return False

		Dim objAsStudent As Students = TryCast(objTemp, Students)

			If objAsStudent Is Nothing Then

				Return False

			Else

				Return Equals(objAsStudent)

			End If

	End Function

	'GetHashCode Method
	Public Overrides Function GetHashCode() As Integer

		Return StudentSurname

	End Function

	'Equals Method
	Public Overloads Function Equals(tempStudent As Students) As Boolean

		If tempStudent Is Nothing Then

			Return False

		End If

		Return (Me.StudentSurname.Equals(tempStudent.StudentSurname))

	End Function

End Class

A lot happens here! Do not worry, it is not too complicated. Allow me to explain:

I added Properties for the Student Class. This gives us a way to get and set the Student name and Surname. Next, I added some methods. These methods enable us to check an object’s existence inside the list, as well as to return the appropriate object when referenced.

Now, let’s use this list of Students inside our form!

Import the Generic Lists namespace:

Imports System.Collections.Generic

Create the physical list:

	'Create List Of Students
	Private lstStudents As List(Of Students) = New List(Of Students)

This creates a list of students – with all its associated properties and methods.

Adding Items to a Generic List

Add the next code segment to the Add button:

	Private Sub btnAdd_Click( sender As Object,  e As EventArgs) Handles btnAdd.Click

		'Add Supplied Student Details To List
		lstStudents.Add(New Students() With { _
			.StudentName = txtStudentName.Text, _
			.StudentSurname = txtStudentSurname.Text _
		})

		txtStudentName.Text = ""
		txtStudentSurname.Text = ""

	End Sub

This adds whatever was entered in the txtStudentName and txtStudentSurname textboxes and adds it to the generic List.

Inserting Items into an Existing Generic List, at a Specific Index

You have to remember, even though it is a generic List, it still has the same capabilities (well, mostly) as an ordinary list. Add the next code:

	Private Sub btnInsertAt_Click( sender As Object,  e As EventArgs) Handles btnInsertAt.Click

		If lstStudents.Count > 2 Then
			lstStudents.Insert(2, New Students() With { _
				.StudentName = txtStudentName.Text, _
				.StudentSurname = txtStudentSurname.Text _
			})

		Else

			MessageBox.Show("List Doesn't Have So Many Items Yet!")

		End If

	End Sub

This checks if there are already items inside the list, and if there are enough, we insert the given text into index number 2.

Removing Items from a Generic List

Add this code to remove the entire Student List:

	Private Sub btnRemove_Click( sender As Object,  e As EventArgs) Handles btnRemove.Click

		'This will remove The ENtire Student even though the StudentName May be different,
		'because the Equals method only checks StudentSurname for equality.

	     lstStudents.Remove(new Students() With { _
				.StudentName = txtStudentName.Text, _
				.StudentSurname = txtStudentSurname.Text _
				})

	End Sub

This removes all the items from the list.

Removing Specific Items from a Generic List

Add this code to remove an item from the list:

	Private Sub btnRemoveAt_Click( sender As Object,  e As EventArgs) Handles btnRemoveAt.Click

		If lstStudents.Count > 2 Then

			lstStudents.RemoveAt(1)

		Else

			MessageBox.Show("List Doesn't Have So Many Items Yet!")

		End If

	End Sub

This removes the item at index 2 from the Student List.

Searching a Generic List

Add the following code:

	Private Sub btnSearch_Click( sender As Object,  e As EventArgs) Handles btnSearch.Click

		 If lstStudents.Contains(New Students() With { _
			.StudentSurname = txtSearch.Text _
				})

			MessageBox.Show("Found!")

			txtSearch.Text = ""
		Else

			MessageBox.Show("Not Found!")

			txtSearch.Text = ""

		End If

	End Sub

Here, I simply made use of the Generic List’s Contains method to determine if the supplied string is present or not. If it is, it will inform the user, else, it will also inform the user. You have to remember that it is case sensitive. If you want to make it case insensitive you’ll have to override the Equals method again.

Displaying Items in a Generic List

Add the next code:

	Private Sub btnShow_Click( sender As Object,  e As EventArgs) Handles btnShow.Click

		lstShowStudents.Items.Clear()

		For Each currStudent As Students In lstStudents

			lstShowStudents.Items.Add(currStudent)

		Next

	End Sub

This code simply loops through the Generic List and adds each item to the ListBox.

Conclusion

Thank you for reading my article. I hope that you have learned something new today and that you will now be able to do any task with a Generic List. Until next time, cheers!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read