Home
VB.NET
Convert List and Array
This page was last reviewed on Apr 21, 2023.
Dot Net Perls
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.
Extension
Convert Dictionary, List
Example. 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.
Step 1 This example creates a List of Integers and then adds 3 elements to it.
Step 2 The program invokes the ToArray extension method on the List of Integers we just created.
Integer
Step 3 It invokes the ToList Extension on the array and assigns the result to another List variable.
ToList
Step 4 The program writes the lengths and counts of the resulting collections to the console.
Console.WriteLine
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 Module
3 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.
List
Array
For
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).
Home
Changes
© 2007-2024 Sam Allen.