VB net List(Of T)

The List Collections.Generic in Visual Basic/C#

byAlexandre

This is a great proof that object oriented programming is good for the evolution, imagine an array like weve seen in the last tutorial, but controlled in a way to make it more efficient and to abstract all the plumbing that is required to expand the array and so on. An easy to use solution!

The Collection.Generics have been invented to simplify our lives so we dont have to implement these complex data structures every time we want to use them.

The most important ones, in my opinion, are the List, the Dictionary, the Queue and the Stack.

They will be divided into one tutorial per collection since I want to give examples and go in more details about each one. The first one were going to go through is the List. After all the Generics have been covered, I will give you a crash course on Linq [maybe after weve seen how objects and classes work], we will then finish this topic.

The List offers more methods and more performance than its younger brother, the ArrayList. You should use a List for general purpose collection operations like storing a list of students for example!

First, lets create a new instance of the List, meaning that were going to use the List class or template if you prefer, to create our own real List object.

Visual Basic

Module Program Sub Main[] ' Create [declare and initialize] a new instance of the Generic class List. Dim ListOfNames = New List[Of String] End Sub End Module

C#

class Program { static void Main[string[] args] { // Create [declare and initialize] a new instance of the Generic class List. List listOfNames = new List[]; } }

This will create a real [because of the New] List object that can contain only String types elements. We are now ready to add data!

Add[T Element]

Its easy to add data to your list, you have to use the method Add[T Element]. Why am I using T as the variable type? Its because you can define your own type of objects that will fit into your list, here we are using Of String but you could use pretty much anything! Here is what it looks like in code.

Visual Basic

Module Program Sub Main[] ' Create a new instance of the Generic class List. Dim ListOfNames = New List[Of String] ' Add 3 elements to the list. ListOfNames.Add["Alexandre"] ListOfNames.Add["Maxime"] ListOfNames.Add["Daniel"] End Sub End Module

C#

class Program { static void Main[string[] args] { // Create a new instance of the Generic class List. List listOfNames = new List[]; // Add 3 elements to the list. listOfNames.Add["Alexandre"]; listOfNames.Add["Maxime"]; listOfNames.Add["Daniel"]; } }

You can also use AddRange[Collection] to add another collections data to this one, very practical because you dont have to loop through all the elements and add them one by one.

Remove[T Element]

Deleting an element from your list is fairly similar, you have to use one of the methods: Remove[T Element], RemoveAt[Integer Index], RemoveAll[Predicate function] or RemoveRange[Integer StartingIndex, Integer Count].

The Remove method lets you remove a specific element, here is an example.

Visual Basic

ListOfNames.Remove["Maxime"]

C#

listOfNames.Remove["Maxime"];

Remark: if the element you wish to remove does not exist, it will not remove anything and will not prompt an error.

Another option is use the RemoveAt[Integer Index] method that will remove an element at a specific Index, for example, Alexandre is at index 0, I can remove this element like that:

Visual Basic

ListOfNames.RemoveAt[0]

C#

listOfNames.RemoveAt[0];

We wont look at the RemoveAll method, we are going to keep that one for later, we need Linq!

As for the RemoveRange method, you can remove from one element counting. For example, if the List contains 5 elements, I can remove the element from 3 to 5 by using this method. Remember that the indexes start at 0!

Visual Basic

ListOfNames.RemoveRange[3, 3]

C#

listOfNames.RemoveRange[3, 3];

The removal starts at 3 and removes 3 elements from the List.

Insert[Integer Position, T Element]

You can insert an element at a specific position in your List with Insert[Integer Position, T Element] method that can be used as follow.

Visual Basic

ListOfNames.Insert[1, "Alexandre"]

C#

listOfNames.Insert[1, "Alexandre"];

In this example, we insert the String element Alexandre at the position 1 in the List.

Contains[T Element]

This method ensures that an element is present in the List, if it is, it will return the Boolean type value True, if it isnt, its going to return False. Thats why you can easily use it in a If statement!

Visual Basic

If ListOfNames.Contains["Alexandre"] Then Console.WriteLine["The list contains the name Alexandre!"] End If

C#

if [listOfNames.Contains["Alexandre"]] Console.WriteLine["The list contains the name Alexandre!"];

The Contains method takes a T Element as parameter, be careful if the element is an object of another type, you may need to implement the IEquatable interface, this is an advanced topic that we will cover later. IF you wish to have more information on that subject, you can refer to the MSDN Website.

Clear[]

The Clear[] method can be used to clear the content of a Collection completely.

Visual Basic

ListOfNames.Clear[]

C#

listOfNames.Clear[];

Debug mode

Again, I strongly suggest that you add breakpoints in this code to better understand how it works and be able to add operations on the List. For example, you can try to do the same thing with a List[Of Integer] or even add numbers with a loop.

Notice that you can click on the small arrow to expand results after you hover on a variable [in this case, the List itself].

Here is the full code I wrote as a reference.

Visual Basic

Module Program Sub Main[] ' Create a new instance of the Generic class List. Dim ListOfNames = New List[Of String] ' Add elements to the List. ListOfNames.Add["Alexandre"] ListOfNames.Add["Maxime"] ListOfNames.Add["Daniel"] ' Remove elements from the List. ListOfNames.Remove["Maxime"] ListOfNames.RemoveAt[0] ' Insert back Alexandre in the List. ListOfNames.Insert[1, "Alexandre"] ' Check if the List contains the element "Alexandre" that we just inserted. If ListOfNames.Contains["Alexandre"] Then Console.WriteLine["The list contains the name Alexandre!"] End If Console.ReadKey[] End Sub End Module

C#

class Program { static void Main[string[] args] { // Create a new instance of the Generic class List. List listOfNames = new List[]; // Add elements to the List. listOfNames.Add["Alexandre"]; listOfNames.Add["Maxime"]; listOfNames.Add["Daniel"]; // Remove elements from the List. listOfNames.Remove["Maxime"]; listOfNames.RemoveAt[0]; // Insert back Alexandre in the List. listOfNames.Insert[1, "Alexandre"]; // Check if the List contains the element "Alexandre" that we just inserted. if [listOfNames.Contains["Alexandre"]] Console.WriteLine["The list contains the name Alexandre!"]; Console.ReadKey[]; } }

These are the basic methods you can use on a list, you will see similarities between other Generic Collections methods. There are more methods that we will need to explore later like Sort[], All[], Select[], Where[], Any[] and so on when we will have a closer look at Linq.

If you need more information on the Lists, please refer to the MSDN Website on the topic or you can always post your questions in the comments.

YouTube

Tags CollectionsVisual Basic

Video liên quan

Chủ Đề