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
exampleThis example demonstrates the AddRange
method. It creates some collections of data and then calls AddRange
to add the array to the List
.
List
and call Add()
4 times. The result is a list with the values 1 through 4 inclusive.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
exampleWhile AddRange
always places elements at the end of the List
, InsertRange
can insert those elements at any valid index.
List
with 4 elements, and an array with 3 elements. We use a shorter syntax in this example.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.