Convert List and ArrayConvert Lists and arrays with the ToArray and ToList Functions.
This page was last reviewed on Mar 26, 2022.
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.
Extension methods. We can perform conversions with the extension methods ToArray and ToList. This is the shortest and clearest way to perform these conversions.
Extension Method
Convert Dictionary, List
Example. This example creates a List of Integers and then adds 3 elements to it. Then, it invokes the ToArray extension method on that collection.
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.
Info The program writes the lengths and counts of the resulting collections to the console.
Module Module1 Sub Main() ' 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) ' Convert the list to an array. Dim array As Integer() = list.ToArray Console.WriteLine(array.Length) ' Convert the array to a list. Dim list2 As List(Of Integer) = array.ToList 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.
For Each, 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 Mar 26, 2022 (rewrite).
© 2007-2022 sam allen.
see site info on the changelog.