Convert Lists and arrays with the ToArray and ToList Functions.
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 do this with the extension methods ToArray and ToList.Array
Example. Initially, this example creates a new List of Integer types and then adds three elements to it. Then, it invokes the ToArray extension method on that collection and assigns the result to a new reference local variable of array type.Integer
Next: It invokes the ToList Extension on the array and assigns the result to another List variable.
Program: This shows how any List and array of equivalent element type can be converted back and forth.
VB.NET program that uses ToArray and ToList
' Create a list and add three elements to it.
Dim list As List(Of Integer) = New List(Of Integer)
' Convert the list to an array.
Dim array As Integer() = list.ToArray
' Convert the array to a list.
Dim list2 As List(Of Integer) = array.ToList
Newer Frameworks required. The ToArray and ToList extension methods are part of the System.Linq namespace in the .NET Framework. This namespace was introduced in .NET 3.5. If you target an older Framework, this example will not work.
Tip: In this case, you can use the List constructor or imperative copying of elements in loops.
Summary. We invoked the ToArray and ToList extension methods to declaratively and clearly convert between list and array types in the VB.NET language. We described the limitations of these methods. They must receive compatible element types.