The design prototype of many standard query operators returns an ienumerable <t> type sequence. These standard query operations are notCodeWhen the row is executed, a sequence is returned. In fact, an object is returned. when the object is enumerated (such as foreach), an element is generated from the ienumerable <t> sequence, and the query operation is actually performed. this is the so-called "latency query ".
A small example proves the existence of "delayed query"
Int [] intarray = new int [] {0, 1, 2, 3}; ienumerable <int> items = intarray. select (I => I); // return I // output result foreach (INT item in items) console. writeline (item); // modify an element in intarray, and then "output result" intarray [0] = 4; console. writeline ("output result after intarray's first element value is changed:"); // output result foreach (INT item in items) console again. writeline (item );
The two output results are: 0, 1, 2, 3, 4, 1, 2, 3. it can be seen that the query operation will be performed only when items is enumerated. if there is no latency query, the two output results should be the same.
Methods To avoid "delayed query"
You can use a conversion operator that does not return the ienumerable <t> data type, such as toarray, tolist, todictionary, or tolookup, so that the query operation will not be delayed. similarly, in the preceding example, if the tolist operator returns a list <int> sequence, no "delayed query" occurs:
Int [] intarray = new int [] {0, 1, 2, 3}; List <int> items = intarray. select (I => I ). tolist (); // added the tolist operator // output result foreach (INT item in items) console. writeline (item); // modify an element in intarray, and then "output result" intarray [0] = 4; console. writeline ("output result after intarray's first element value is changed:"); // output result foreach (INT item in items) console again. writeline (item );
In this way, both outputs are 0, 1, 2, and 3.
Possible errors caused by "delayed query"
A query is executed only when it is enumerated due to latency, therefore, if the Program is compiled, but it does not mean that this query is okay. for example, to query the 3rd characters of each element in a string array, if the length of a string is <3, an error is reported during running, the program is no problem during compilation.