ToList Extension ExampleUse the ToList Extension on an array. ToList internally uses the List constructor.
This page was last reviewed on Mar 11, 2022.
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?
Method notes. 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.
Extension Method
Example. This program first creates an array of 4 String literals. We then invoke ToList. The resulting List has 4 elements and contains all the same elements as the originating array.
So At this point, we can add elements to our List collection dynamically, as with Add. This could not be done with the array.
Module Module1 Sub Main() ' Create array. Dim array() As String = {"A", "B", "C", "D"} ' Create List. Dim list As List(Of String) = array.ToList() ' Display Count. Console.WriteLine(list.Count) ' Display each item. For Each item As String In list Console.WriteLine(" {0}", item) Next End Sub End Module
4 A B C D
Discussion. When you call the ToList Extension, a few internal checks occur. The parameter (the instance ToList is called on) is checked for Nothing.
And Then, depending on the type of the argument, the List constructor is called.
Note This means that, when you know the type of the instance is an array, using the List constructor directly is more efficient.
Info This bypasses logic tests. 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)
Summary. 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.
Convert List, Array
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 11, 2022 (edit).
© 2007-2023 Sam Allen.