InternetUnicodeHTMLCSSScalable Vector Graphics (SVG)Extensible Markup Language (xml) ASP.Net TOCASP.NetMiscellaneous Feature ASP.NET Scripting Visual Basic .NET TOCVB .NET Language Referencena VB.Net KeywordsVB.Net DataVB.Net Declared ElementVB.Net DelegatesVB.Net Object CharacteristicsVB.Net EventsVB.Net InterfacesVB.Net LINQVB.Net Object and ClassVB.Net Operators and ExpressionsVB.Net ProceduresVB.Net StatementsVB.Net StringsVB.Net XMLConstants and LiteralsVB .NET EnumerationsVB .NET Data TypesVB .NET VariableVB .NET Array Collections Draft for Information Only
Content
VB.NET Collection Initializers
VB.NET Collection InitializersCollection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values. Collection initializers are useful when you are creating a collection from a set of known values, for example, a list of menu options or categories, an initial set of numeric values, a static list of strings such as day or month names, or geographic locations such as a list of states that is used for validation. For more information about collections, see Collections. You identify a collection initializer by using the From keyword followed by braces ({}). This is similar to the array literal syntax that is described in Arrays. The following examples show various ways to use collection initializers to create collections. VB' Create an array of type String(). Dim winterMonths = {"December", "January", "February"} ' Create an array of type Integer() Dim numbers = {1, 2, 3, 4, 5} ' Create a list of menu options. (Requires an extension method ' named Add for List(Of MenuOption) Dim menuOptions = New List(Of MenuOption) From {{1, "Home"}, {2, "Products"}, {3, "News"}, {4, "Contact Us"}} Note C# also provides collection initializers. C# collection initializers provide the same functionality as Visual Basic collection initializers. For more information about C# collection initializers, see Object and Collection Initializers. SyntaxA collection initializer consists of a list of comma-separated values that are enclosed in braces ({}), preceded by the From keyword, as shown in the following code. VBDim names As New List(Of String) From {"Christa", "Brian", "Tim"} When you create a collection, such as a List<T> or a Dictionary<TKey,TValue>, you must supply the collection type before the collection initializer, as shown in the following code. VBPublic Class AppMenu Public Property Items As List(Of String) = New List(Of String) From {"Home", "About", "Contact"} End Class Note You cannot combine both a collection initializer and an object initializer to initialize the same collection object. You can use object initializers to initialize objects in a collection initializer. Creating a Collection by Using a Collection InitializerWhen you create a collection by using a collection initializer, each value that is supplied in the collection initializer is passed to the appropriate Add method of the collection. For example, if you create a List<T> by using a collection initializer, each string value in the collection initializer is passed to the Add method. If you want to create a collection by using a collection initializer, the specified type must be valid collection type. Examples of valid collection types include classes that implement the IEnumerable<T> interface or inherit the CollectionBase class. The specified type must also expose an Add method that meets the following criteria.
For example, the following code example shows how to create a List(Of Customer) collection by using a collection initializer. When the code is run, each Customer object is passed to the Add(Customer) method of the generic list. VBDim customers = New List(Of Customer) From { New Customer("City Power & Light", "http://www.cpandl.com/"), New Customer("Wide World Importers", "http://www.wideworldimporters.com/"), New Customer("Lucerne Publishing", "http://www.lucernepublishing.com/") } The following code example shows equivalent code that does not use a collection initializer. VBDim customers = New List(Of Customer) customers.Add(New Customer("City Power & Light", "http://www.cpandl.com/")) customers.Add(New Customer("Wide World Importers", "http://www.wideworldimporters.com/")) customers.Add(New Customer("Lucerne Publishing", "http://www.lucernepublishing.com/")) If the collection has an Add method that has parameters that match the constructor for the Customer object, you could nest parameter values for the Add method within collection initializers, as discussed in the next section. If the collection does not have such an Add method, you can create one as an extension method. For an example of how to create an Add method as an extension method for a collection, see How to: Create an Add Extension Method Used by a Collection Initializer. For an example of how to create a custom collection that can be used with a collection initializer, see How to: Create a Collection Used by a Collection Initializer. Nesting Collection InitializersYou can nest values within a collection initializer to identify a specific overload of an Add method for the collection that is being created. The values passed to the Add method must be separated by commas and enclosed in braces ({}), like you would do in an array literal or collection initializer. When you create a collection by using nested values, each element of the nested value list is passed as an argument to the Add method that matches the element types. For example, the following code example creates a Dictionary<TKey,TValue> in which the keys are of type Integer and the values are of type String. Each of the nested value lists is matched to the Add method for the Dictionary. VBDim days = New Dictionary(Of Integer, String) From {{0, "Sunday"}, {1, "Monday"}} The previous code example is equivalent to the following code. VBDim days = New Dictionary(Of Integer, String) days.Add(0, "Sunday") days.Add(1, "Monday") Only nested value lists from the first level of nesting are sent to the Add method for the collection type. Deeper levels of nesting are treated as array literals and the nested value lists are not matched to the Add method of any collection. Related Topics
See also
How to: Create an Add Extension Method Used by a Collection InitializerWhen you use a collection initializer to create a collection, the Visual Basic compiler searches for an Add method of the collection type for which the parameters for the Add method match the types of the values in the collection initializer. This Add method is used to populate the collection with the values from the collection initializer. If no matching Add method exists and you cannot modify the code for the collection, you can add an extension method called Add that takes the parameters that are required by the collection initializer. This is typically what you need to do when you use collection initializers for generic collections. ExampleThe following example shows how to add an extension method to the generic List<T> type so that a collection initializer can be used to add objects of type Employee. The extension method enables you to use the shortened collection initializer syntax. VBPublic Class Employee Public Property Id() As Integer Public Property Name() As String End ClassVB Imports System.Runtime.CompilerServices Module Module1 <Extension()> Sub Add(ByVal list As List(Of Employee), ByVal id As Integer, ByVal name As String) list.Add(New Employee With {.Id = id, .Name = name}) End Sub End ModuleVB Sub Main() Dim employees = New List(Of Employee) From {{1, "Adams, Ellen"}, {2, "Hamilton, James R."}, {3, "Ihrig, Ryan"}} End Sub See alsoHow to: Create a Collection Used by a Collection InitializerWhen you use a collection initializer to create a collection, the Visual Basic compiler searches for an Add method of the collection type for which the parameters for the Add method match the types of the values in the collection initializer. This Add method is used to populate the collection with the values from the collection initializer. ExampleThe following example shows an OrderCollection collection that contains a public Add method that a collection initializer can use to add objects of type Order. The Add method enables you to use the shortened collection initializer syntax. VBPublic Class Customer Public Property Id As Integer Public Property Name As String Public Property Orders As OrderCollection Public Sub New(ByVal id As Integer, ByVal name As String, ByVal orders As OrderCollection) Me.Id = id Me.Name = name Me.Orders = orders End Sub End Class Public Class Order Public Property Id As Integer Public Property CustomerId As Integer Public Property OrderDate As DateTime Public Sub New(ByVal id As Integer, ByVal customerId As Integer, ByVal orderDate As DateTime) Me.Id = id Me.CustomerId = customerId Me.OrderDate = orderDate End Sub End ClassVB Public Class OrderCollection Implements IEnumerable(Of Order) Dim items As New List(Of Order) Public Property Item(ByVal index As Integer) As Order Get Return CType(Me(index), Order) End Get Set(ByVal value As Order) items(index) = value End Set End Property Public Sub Add(ByVal id As Integer, ByVal customerID As Integer, ByVal orderDate As DateTime) items.Add(New Order(id, customerID, orderDate)) End Sub Public Function GetEnumerator() As IEnumerator(Of Order) Implements IEnumerable(Of Order).GetEnumerator Return items.GetEnumerator() End Function Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return Me.GetEnumerator() End Function End ClassVB Imports System.Runtime.CompilerServices Module Module1 <Extension()> Sub Add(ByVal genericList As List(Of Customer), ByVal id As Integer, ByVal name As String, ByVal orders As OrderCollection) genericList.Add(New Customer(id, name, orders)) End Sub End ModuleVB Dim customerList = New List(Of Customer) From { {1, "John Rodman", New OrderCollection From {{9, 1, #6/12/2008#}, {8, 1, #6/11/2008#}, {5, 1, #5/1/2008#}}}, {2, "Ariane Berthier", New OrderCollection From {{2, 2, #1/18/2008#}, {4, 2, #3/8/2008#}, {6, 2, #3/18/2008#}, {7, 2, #5/14/2008#}, {5, 2, #4/4/2008#}}}, {3, "Brian Perry", New OrderCollection From {{1, 3, #1/15/2008#}, {3, 3, #3/8/2008#}}} } See alsoSource/Reference
©sideway ID: 200900015 Last Updated: 9/15/2020 Revision: 0 Ref: References
Latest Updated Links
|
Home 5 Business Management HBR 3 Information Recreation Hobbies 8 Culture Chinese 1097 English 339 Travel 7 Reference 79 Computer Hardware 251 Software Application 213 Digitization 32 Latex 52 Manim 205 KB 1 Numeric 19 Programming Web 289 Unicode 504 HTML 66 CSS 65 SVG 46 ASP.NET 270 OS 431 DeskTop 7 Python 72 Knowledge Mathematics Formulas 8 Set 1 Logic 1 Algebra 84 Number Theory 206 Trigonometry 31 Geometry 34 Calculus 67 Engineering Tables 8 Mechanical Rigid Bodies Statics 92 Dynamics 37 Fluid 5 Control Acoustics 19 Natural Sciences Matter 1 Electric 27 Biology 1 |
Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019