Home
VB.NET
Convert List and Array
Updated 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 21, 2023 (rewrite).
Home
Changes
© 2007-2025 Sam Allen