198Microsoft Visual Studio 2010: A Beginner’s Guide

Creating a LINQ Projection with Anonymous Types

You can customize what is returned by the select clause by using what is called an anonymous type. This customization of return values is called a projection. Anonymous types facilitate custom projections, allowing you to return the results of a LINQ query in a form that you specify without needing to declare a new type ahead of time. Here’s an example of creating a query that declares a new anonymous type for combining the FirstName and LastName properties of Customer into a variable, FullName, that is created as a string-type property associated with the object returned into cust in the foreach statement:

C#:

var customers =

from cust in custList

where cust.FirstName.StartsWith("M") select new

{

FullName = cust.FirstName + " " + cust.LastName

};

foreach (var cust in customers)

{

Console.WriteLine(cust.FullName);

}

VB:

Dim customers =

From cust In custList

Where cust.FirstName.StartsWith("M") Select New With

{

.FullName = cust.FirstName & " " & cust.LastName

}

For Each cust In customers

Console.WriteLine(cust.FullName)

Next

In both the C# and VB select clauses you see a new statement (New With in VB) that defines the anonymous type. The new anonymous type has a single property, FullName, that is the combination of FirstName and LastName in Customer, but the new type will

Page 221
Image 221
Microsoft 9GD00001 manual Creating a Linq Projection with Anonymous Types