ToArray Example
This page was last reviewed on Jan 18, 2024.
Dot Net Perls
ToArray. The IEnumerable type can store collections of elements. But in VB.NET programs, we often want arrays—not IEnumerable instances.
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.
Example. ToArray is found within System.Linq. It can be called on any type instance that implements IEnumerable. Many types implement IEnumerable.
Step 1 This program creates a List with 2 strings. This is not an array, but we can call ToArray on it.
Step 2 We create an IEnumerable instance with 10 elements in it with Enumerable.Range.
Step 3 The program calls the ToArray extension on the List and IEnumerable. We now have 2 arrays.
Step 4 We use a For-Each loop on both the first and second arrays to print out all the contents.
Module Module1 Sub Main() ' Step 1: create a List. Dim list = New List(Of String) list.Add("BIRD") list.Add("FROG") ' Step 2: create an IEnumerable. Dim e = Enumerable.Range(0, 10) ' Step 3: use ToArray extension to convert to an array. Dim array1() = list.ToArray() Dim array2() = e.ToArray() ' Step 4: 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.
Also Some collections, such as List, offer a separate ToArray Function. This is not an extension method.
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 Jan 18, 2024 (edit).
© 2007-2024 Sam Allen.