The Select clause specifies the form and content of returned elements. For example, you can specify whether your results will consist of complete Customer objects, just one Customer property, a subset of properties, a combination of properties from various data sources, or some new result type based on a computation. When the Select clause produces something other than a copy of the source element, the operation is called a projection.
To retrieve a collection that consists of complete Customer objects, select the range variable itself:
Dim londonCusts2 = From cust In customers _
Where cust.City = "London" _
Order By cust.Name Ascending _
Select cust
If a Customer instance is a large object that has many fields, and all that you want to retrieve is the name, you can select cust.Name, as shown in the following example. Local type inference recognizes that this changes the result type from a collection of Customer objects to a collection of strings.
Dim londonCusts3 = From cust In customers _
Where cust.City = "London" _
Order By cust.Name Ascending _
Select cust.Name
To select multiple fields from the data source, you have two choices:
In the Select clause, specify the fields you want to include in the result. The compiler will define an anonymous type that has those fields as its properties. For more information, see Anonymous Types.
Because the returned elements in the following example are instances of an anonymous type, you cannot refer to the type by name elsewhere in your code. The compiler-designated name for the type contains characters that are not valid in normal Visual Basic code. In the following example, the elements in the collection that is returned by the query in londonCusts4 are instances of an anonymous type
Dim londonCusts4 = From cust In customers _
Where cust.City = "London" _
Order By cust.Name Ascending _
Select Name = cust.Name, Phone = cust.Phone
For Each londonCust In londonCusts4
Console.WriteLine(londonCust.Name & " " & londonCust.Phone)
Next
-or-
Define a named type that contains the particular fields that you want to include in the result, and create and initialize instances of the type in the Select clause. Use this option only if you have to use individual results outside the collection in which they are returned, or if you have to pass them as parameters in method calls. The type of londonCusts5 in the following example is IEnumerable(Of NamePhone).
Public Class NamePhone
Public Name As String
Public Phone As String
' Additional class elements
End Class
Dim londonCusts5 = From cust In customers _
Where cust.City = "London" _
Order By cust.Name Ascending _
Select New NamePhone With {.Name = cust.Name, _
.Phone = cust.Phone}
For more information about how to use the Select clause in Visual Basic, see Select Clause (Visual Basic).