List
, arrayLists 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.
A List
and array of equivalent element type can be converted back and forth. The example uses a List
of Integers, but any type could be used.
List
of Integers and then adds 3 elements to it.ToArray
extension method on the List
of Integers we just created.ToList
Extension on the array and assigns the result to another List
variable.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
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.
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.