Equality | EqualAll |
Generation | Empty , Range , Repeat |
Grouping | GroupBy |
Joining | GroupJoin , Join |
Ordering | OrderBy , ThenBy , OrderByDescending , ThenByDescending , Reverse |
Partitioning | Skip , SkipWhile , Take , TakeWhile |
Quantifiers | All , Any , Contains |
Restriction | Where |
Selection | Select , SelectMany |
Set | Concat , Distinct , Except , Intersect , Union |
The query variable itself only stores the query; it does not execute the query or store the result.
Take another look at the preceding example:
int[] nums = {
12, 34, 10, 3, 45, 6, 90, 22, 87, 49, 13, 32
};
var oddNums = nums.Where
(n => n % 2 == 1).OrderByDescending(n => n);
The oddNums
variable simply stores the query (not the result of the query). The query is only executed when you iterate over the query variable, like this:
foreach (int n in oddNums)
Console.WriteLine(n);
This concept is known as
To prove that deferred execution really works, the following program first defines a query and then prints out the result using a foreach
loop. Twenty is added to each element in the array, and then the foreach
loop is executed again.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5 {
class Program {
static void Main(string[] args) {
int[] nums = {
12, 34, 10, 3, 45, 6, 90, 22, 87, 49, 13, 32
};
var oddNums =
nums.Where(n => n % 2 == 1).OrderByDescending(n => n);
Console.WriteLine('First execution');
Console.WriteLine('---------------');
foreach (int n in oddNums) Console.WriteLine(n);
//---add 20 to each number in the array---
for (int i = 0; i < 11; i++) nums[i] += 20;
Console.WriteLine('Second execution');
Console.WriteLine('----------------');
foreach (int n in oddNums) Console.WriteLine(n);
Console.ReadLine();
}
}
}
The program prints out the following output:
First execution
---------------
87
49
45
13
3
Second execution
107
69