AddRange, InsertRange. Often in VB.NET programs we need to add just one element at a time to a List. But sometimes, an entire array of elements must be appended or inserted at once.
By using AddRange and InsertRange, we can avoid writing verbose loops to add these elements. Just a single statement is required to add many elements to a List.
AddRange example. This example demonstrates the AddRange method. It creates some collections of data and then calls AddRange to add the array to the List.
Step 1 We create a List and call Add() 4 times. The result is a list with the values 1 through 4 inclusive.
Step 2 We create a new array. In VB.NET, when we create an array we can specify the "last index" of the array as its type.
Step 3 We invoke AddRange, passing the array to the AddRange method, and then display the updated contents of the List.
Module Module1
Sub Main()
' Step 1: create List.
Dim list = New List(Of Integer)()
list.Add(1)
list.Add(2)
list.Add(3)
list.Add(4)
' Step 2: new array with maximum index syntax.
Dim array(2) as Integer
array(0) = 100
array(1) = 200
array(2) = 300
' Step 3: call AddRange and display the updated List contents.
list.AddRange(array)
For Each value in list
Console.WriteLine("LIST: {0}", value)
Next
End Sub
End ModuleLIST: 1
LIST: 2
LIST: 3
LIST: 4
LIST: 100
LIST: 200
LIST: 300
InsertRange example. While AddRange always places elements at the end of the List, InsertRange can insert those elements at any valid index.
Part 1 We create a List with 4 elements, and an array with 3 elements. We use a shorter syntax in this example.
Part 2 We insert all the elements from the array at index 1, which is after the first element. We then display the List elements.
Module Module1
Sub Main()
' Part 1: create data collections.
Dim list = New List(Of Integer)({ 1, 2, 3, 4 })
Dim array = { 500, 600, 700 }
' Part 2: call InsertRange and display the elements afterwards.
list.InsertRange(1, array)
For Each value in list
Console.WriteLine($"ELEMENT: {value}")
Next
End Sub
End ModuleELEMENT: 1
ELEMENT: 500
ELEMENT: 600
ELEMENT: 700
ELEMENT: 2
ELEMENT: 3
ELEMENT: 4
In developing VB.NET programs, it is often helpful to reduce excessive lines of code. With AddRange and InsertRange, we can eliminate For-loops in our functions.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.