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.
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 ModuleBIRD
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 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 Jan 18, 2024 (edit).