Convert List, array. Lists and arrays are often converted. Both the List and array types in the VB.NET language are useful. But sometimes we require the opposite type.
We can perform conversions with the extension methods ToArray and ToList. This is the shortest and clearest way to perform these conversions.
Module Module1
Sub Main()
' Step 1: create a list and add 3 elements to it.
Dim list As List(Of Integer) = New List(Of Integer)
list.Add(1)
list.Add(2)
list.Add(3)
' Step 2: convert the list to an array.
Dim array As Integer() = list.ToArray
Console.WriteLine(array.Length)
' Step 3: convert the array to a list.
Dim list2 As List(Of Integer) = array.ToList
' Step 4: display.
Console.WriteLine(list2.Count)
End Sub
End Module3
3
A discussion. The ToArray and ToList extension methods are part of the System.Linq namespace in the .NET Framework. We could also use the List constructor or copy elements in a For-loop.
Summary. We invoked the ToArray and ToList extension methods to convert between list and array types. We described the limitations of these methods. They must receive compatible element types.
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 Apr 21, 2023 (rewrite).