Fill an ArrayList from an Array

Problem

You need to copy items from an array into an ArrayList.

Solution

You can add an entire range of items into an ArrayList quickly using the AddRange method.

Discussion

The ArrayList.AddRange method accepts any object that implements the ICollection interface (including an array or another ArrayList), and copies all the items it contains into the ArrayList.

Dim Colors() As String = {"blue", "green", "pink", "yellow"}

' Copy the strings in the Colors array into the List ArrayList.
Dim List As New ArrayList()
List.AddRange(Colors)

' Display the contents of the ArrayList.
Dim Item As String
For Each Item In List
    Console.WriteLine(Item)
Next

Keep in mind that if you are using a reference type, when you copy it into the ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.