How to use LINQ expression to do projection in VB.NET

Web developer can use approach described in the article How to use LINQ expression to get a subset of data in VB.NET to define a new class that wraps just the information he/she wants to return. For example, if he/she wants to get both the first and last names but he/she wants to store them in separate strings, he/she could create a stripped-down version of the Client class that includes just a FirstName and LastName property. To do so, Web developer uses a VB.NET feature known as anonymous types. The basic technique is to add the new keyword to the select clause, followed by a pair of curly braces. Then, inside the braces,he/she assigns each property he/she wants to create in terms of the object he/she’s selecting:

Dim matches = From client In clients _

Select New With { .Firts = client.FirstName, .Last = client.LastName}

This expression, when executed, returns a set of objects that use an implicitly created class. Each object has two properties: First and Last. Web developer never sees the class definition, because it’s generated by the compiler and given a meaningless, automatically created name. Web developer can still use the class locally, access the First and Last properties, and even use it with data binding (in which case ASP.NET extracts the appropriate values by property name, using reflection). The ability to transform the data he/she’s querying into results with a different structure is called projection.

 

When Web developer doesn’t need to use anonymous types, he/she can define the type formally and then use it in his/her expression. For example, Web developer can create the following class:

 

Public Class ClientNames

Private _FirstName As String

Private _LastName As String

Public Property FirstName() As String

Get

Return _FirstName

End Get

Set(ByVal value As String)

_FirstName = value

End Set

End Property

Public Property LastName() As String

Get

Return _LastName

End Get

Set(ByVal value As String)

_LastName = value

End Set

End Property

End Class

 

and he/she could change Client objects in ClientNames objects in his/her query expression like this:

 

Dim matches = From client In clients _

Select New ClientNames With {.FirstName = client.FirstName, .LastName = client.LastName}

 

This query expression works because the FirstName and LastName properties are publicly accessible and aren’t read-only. After creating the ClientNames object, LINQ sets these properties.