
Anonymous Types from Query Expressions
Query expressions do not always require the creation of anonymous types. When possible, they use an existing type to hold the column data. This occurs when the query returns either whole records from the data source, or only one field from each record. In the following code examples, customers is a collection of objects of a Customer class. The class has many properties, and you can include one or more of them in the query result, in any order. In the first two examples, no anonymous types are required because the queries select elements of named types:
custs1 contains a collection of strings, because cust.Name is a string.
Dim custs1 = From cust In customers _
Select cust.Name
custs2 contains a collection of Customer objects, because each element of customers is a Customer object, and the whole element is selected by the query.
Dim custs2 = From cust In customers _
Select cust
However, appropriate named types are not always available. You might want to select customer names and addresses for one purpose, customer ID numbers and locations for another, and customer names, addresses, and order histories for a third. Anonymous types enable you to select any combination of properties, in any order, without first declaring a new named type to hold the result. Instead, the compiler creates an anonymous type for each compilation of properties. The following query selects only the customer's name and ID number from each Customer object in customers. Therefore, the compiler creates an anonymous type that contains only those two properties.
Dim custs3 = From cust In customers _
Select cust.Name, cust.ID
Both the names and the data types of the properties in the anonymous type are taken from the arguments to Select, cust.Name and cust.ID. The properties in an anonymous type that is created by a query are always key properties. When custs3 is executed in the following For Each loop, the result is a collection of instances of an anonymous type with two key properties, Name and ID.
For Each selectedCust In custs3
Console.WriteLine(selectedCust.ID & ": " & selectedCust.Name)
Next
The elements in the collection represented by custs3 are strongly typed, and you can use IntelliSense to navigate through the available properties and to verify their types.
For more information, see Introduction to LINQ in Visual Basic.