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
Deferred Query Execution

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 deferred execution, and it means that every time you access the query variable, the query is executed again. This is useful because you can just create one query and every time you execute it you will always get the most recent result.

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

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату