| title | ms.date | ms.prod | ms.technology | ms.topic | f1_keywords | dev_langs | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | translation.priority.ht | |||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
select clause (C# Reference) |
2015-07-20 |
.net |
|
article |
|
|
|
df01e266-5781-4aaa-80c4-67cf28ea093f |
19 |
BillWagner |
wiwagn |
|
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.
[!code-cscscsrefQueryKeywords#8]
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#).
Example
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 (studentQuery1, studentQuery2, and so on).
[!code-cscscsrefQueryKeywords#9]
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.
Remarks
At compile time, the select clause is translated to a method call to the xref:System.Linq.Enumerable.Select%2A standard query operator.
See Also
C# Reference
Query Keywords (LINQ)
from clause
partial (Method) (C# Reference)
Anonymous Types
LINQ Query Expressions
Getting Started with LINQ in C#