from clause
Learn to start query syntax with from.
The from clause
Query syntax is a SQL-like way to write LINQ queries. Every query starts with from. It declares a range variable and the data source: from n in numbers.
Here n represents each element; numbers is the source. The range variable is in scope for the rest of the query, much like the iteration variable in foreach. Query syntax is preferred when method chains feel less readable.
The range variable
The range variable is a name in scope for the rest of the query. In from n in numbers, n is the range variable. You use it in the remaining clauses (where, select, orderby).
It is similar to the iteration variable in foreach, but the query is not executed yet — only defined. It runs when you loop over it with foreach or call ToList().
Exercise Write your first query syntax query
Write a query from n in numbers select n for the numbers array below. Iterate the result with foreach and print each element with Console.WriteLine(n).
Show example solution
Start the query with from n in numbers, end with select 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;
foreach (var n in query)
{
Console.WriteLine(n);
}
}
}
Test yourself
-
What does the from clause do?
- It ends the query
- It declares a range variable and specifies the source
- It applies a filter predicate
- It performs sorting
Show answer
It declares a range variable and specifies the source — Correct. from declares the range variable and the data source.
-
Complete the from clause
var query = ____ n in numbers select n;Show answer
var query = from n in numbers select n; -
Match each clause to its role
- from
- Starts the query
- where
- Filters
- select
- Projects
- orderby
- Sorts