TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to VBNET

VB.NET ToList Extension Example

Use the ToList Extension on an array. ToList internally uses the List constructor.
ToList. Often in programs we have arrays. But we want those arrays to be used as Lists. What is the easiest way to convert a collection into a List? In VB.NET, we have access to an Extension called ToList.ListLINQ
Example. This program first creates an array of 4 String literals. We then invoke the ToList Extension on this array. The resulting List has four elements and contains all the same elements as the originating array.

So: At this point, we can add elements to our List collection dynamically, as with Add. This could not be done with the array.

VB.NET program that uses ToList Extension Module Module1 Sub Main() ' Create array. Dim array() As String = {"A", "B", "C", "D"} ' Create List. Dim list As List(Of String) = array.ToList() ' Display Count. Console.WriteLine(list.Count) ' Display each item. For Each item As String In list Console.WriteLine(" {0}", item) Next End Sub End Module Output 4 A B C D
Discussion. When you call the ToList Extension, a few internal checks occur. The parameter (the instance ToList is called on) is checked for Nothing. And then, depending on the type of the argument, the List constructor is called.
This means that, when you know the type of the instance is an array, using the List constructor directly is more efficient. This bypasses logic tests. ToList should only be used on types that cannot be passed to the List constructor.
Statement that uses ToList: VB.NET ' Create List. Dim list As List(Of String) = array.ToList() Statement that uses List constructor: VB.NET ' Create List: same result. Dim list As List(Of String) = New List(Of String)(array)
Summary. The List type is often preferred in programs for its dynamic resizing. It is easier to use than an array. A List results in some performance drawbacks, but these are usually of no importance.Convert List, Array
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf