The following example shows a simple query expression and the semantically equivalent query written as a method-based query.
class QueryVMethodSyntax
{
static void Main()
{
int[] numbers = { 5, 10, 8, 3, 6, 12};
//Query syntax:
IEnumerable
from num in numbers
where num % 2 == 0
orderby num
select num;
//Method syntax:
IEnumerable
foreach (int i in numQuery1)
{
Console.Write(i + " ");
}
Console.WriteLine(System.Environment.NewLine);
foreach (int i in numQuery2)
{
Console.Write(i + " ");
}
// Keep the console open in debug mode.
Console.WriteLine(System.Environment.NewLine);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
/*
Output:
6 8 10 12
6 8 10 12
*/
The output from the two examples is identical. You can see that the type of the query variable is the same in both forms: IEnumerable<(Of <(T>)>).
To understand the method-based query, let's examine it more closely. On the right side of the expression, notice that the where clause is now expressed as an instance method on the numbers object, which as you will recall has a type of IEnumerable
Although it looks as if IEnumerable<(Of <(T>)>) has been redefined to include these additional methods, in fact this is not the case. The standard query operators are implemented as a new kind of method called extension methods. Extensions methods "extend" an existing type; they can be called as if they were instance methods on the type. The standard query operators extend IEnumerable<(Of <(T>)>) and that is why you can write numbers.Where(...).
No comments:
Post a Comment