select in query
Learn projection with select in query syntax.
Projection with select
select transforms each element (projection). It comes at the end of the query and is mandatory. The transform is any expression over the range variable: from n in numbers select n * 2.
The result is a sequence of the projected type. select n * 2 yields an int sequence; select n.ToString() yields a string sequence. Anonymous types work too: select new { n, Sq = n * n }.
select or group
A query must end with either select or group ... by. select projects; group clusters. You cannot have both; the query takes a single ending clause.
Sometimes select does not need to transform; select n passes the element through unchanged. Still, you must write it. This lets the compiler know where the query ends.
Exercise Produce squares with select
Project each number to its square with select n * n in the numbers array. Iterate with foreach and print with Console.WriteLine(n).
Show example solution
Write from n in numbers select n * n;. Then loop with foreach (var n in query) { Console.WriteLine(n); }.
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
var query = from n in numbers
select n * n;
foreach (var n in query)
{
Console.WriteLine(n);
}
}
}
Test yourself
-
Match select expression to result type
- select n
- Number sequence
- select n * 2
- Doubled sequence
- select n.ToString()
- String sequence
- select new { n, Sq = n*n }
- Anonymous type sequence
-
Complete the select projection
var query = from n in numbers select ____;Show answer
var query = from n in numbers select n * 2; -
What is the purpose of select?
- To filter
- To sort
- To group
- To transform each element
Show answer
To transform each element — Correct. select transforms each element (projection).