select clause - C# Reference
select clause (C# Reference)
In a query expression, the
select clause specifies the type of values that will be produced when the query is executed. The result is based on the evaluation of all the previous clauses and on any expressions in the
select clause itself. A query expression must terminate with either a
select clause or a group clause.
The following example shows a simple
select clause in a query expression.
The type of the sequence produced by the
select clause determines the type of the query variable
queryHighScores. In the simplest case, the
select clause just specifies the range variable. This causes the returned sequence to contain elements of the same type as the data source. For more information, see Type Relationships in LINQ Query Operations. However, the
select clause also provides a powerful mechanism for transforming (or projecting) source data into new types. For more information, see Data Transformations with LINQ (C#).
The following example shows all the different forms that a
select clause may take. In each query, note the relationship between the
select clause and the type of the query variable (
studentQuery2, and so on).
As shown in
studentQuery8 in the previous example, sometimes you might want the elements of the returned sequence to contain only a subset of the properties of the source elements. By keeping the returned sequence as small as possible you can reduce the memory requirements and increase the speed of the execution of the query. You can accomplish this by creating an anonymous type in the
select clause and using an object initializer to initialize it with the appropriate properties from the source element. For an example of how to do this, see Object and Collection Initializers.
At compile time, the
select clause is translated to a method call to the xref:System.Linq.Enumerable.Select%2A standard query operator.