ToList
Often in VB.NET programs we have arrays. But we want those arrays to be used as Lists. What is the easiest way to convert a collection into a List
?
In VB.NET, we have access to an Extension called ToList
. We can call ToList
directly upon an array. An array of any type of elements can be used.
In VB.NET programs, we often can benefit from the features of Lists, such as dynamic resizing. This motivates us to convert from arrays to Lists.
String
literals.ToList
. The resulting List
has 4 elements and contains all the same elements as the originating array.For-Each
loop to iterate over the elements in the newly-created List
and print each one to the Console
.List
collection dynamically, as with Add. This could not be done with the array.Module Module1 Sub Main() ' Step 1: create array. Dim array() As String = {"A", "B", "C", "D"} ' Step 2: create List and print Count. Dim list As List(Of String) = array.ToList() Console.WriteLine(list.Count) ' Step 3: display each item. For Each item As String In list Console.WriteLine(" {0}", item) Next End Sub End Module4 A B C D
When you call the ToList
Extension, a few internal checks occur. The parameter (the instance ToList
is called on) is checked for Nothing.
List
constructor is called.List
constructor directly is more efficient.ToList
should only be used on types that cannot be passed to the List
constructor.' Create List. Dim list As List(Of String) = array.ToList()' Create List: same result. Dim list As List(Of String) = New List(Of String)(array)
The List
type is often preferred in programs for its dynamic resizing. It is easier to use than an array. A List
results in some performance drawbacks.