Home
Search
VB.NET ToArray ExampleUse the ToArray extension Function to convert an IEnumerable to an array.
ToArray. The IEnumerable type can store collections of elements. But in VB.NET programs, we often want arrays—not IEnumerable instances.
Array
ToArray usage. We use the ToArray extension to convert any IEnumerable type to an array. Common IEnumerable types include Lists and query expressions from LINQ.
List
LINQ
An example. This program creates a List with 2 strings It also creates an IEnumerable instance with 10 elements in it. These elements are not arrays, but we can call ToArray on them.
Then The program calls the ToArray extension on the List and IEnumerable We now have 2 arrays.
Tip ToArray is found within System.Linq. It can be called on any type instance that implements IEnumerable.
IEnumerable
Tip 2 Many types implement IEnumerable. And we can even use the IEnumerable type itself—this is what we do in this program.
Enumerable.Range The example also uses Enumerable.Range to quickly get an IEnumerable of Integers.
Range, Repeat, Empty
Module Module1 Sub Main() ' Create a List. Dim list = New List(Of String) list.Add("BIRD") list.Add("FROG") ' Create an IEnumerable. Dim e = Enumerable.Range(0, 10) ' Use ToArray extension to convert to an array. Dim array1() = list.ToArray() Dim array2() = e.ToArray() ' Display elements. For Each value In array1 Console.WriteLine(value) Next For Each i In array2 Console.WriteLine(i) Next End Sub End Module
BIRD FROG 0 1 2 3 4 5 6 7 8 9
Internals. I investigated the ToArray extension Function. This Function allocates a new array. It then calls into Array.Copy. This newly-allocated array is returned to the calling Function.
Performance. By looking at its implementation, we can determine there is no performance benefit to calling ToArray. It can improve program syntax.
Benchmarks
Also Some collections, such as List, offer a separate ToArray Function. This is not an extension method.
A summary. We explored the ToArray extension Function from System.Linq. We used it with an IEnumerable instance and the Enumerable.Range Function. And we investigated its internals.
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 12/8/2021 (image).
Home
© 2007-2022 sam allen.
see site info on the changelog.