How to use LINQ expression to do projection in C#

Web developer can use approach described in the article How to use LINQ expression to get a subset of data in C# 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 C# 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:

var matches = from client in clients

select new { First = 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

{

public string FirstName { get; set; }

public string LastName { get; set; }

}

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