The LINQ query expression does not actually perform operations before the content is iterated. This is called delayed execution. The advantage of this method is that the same LINQ query can be applied multiple times for the same container, and the latest results are always obtained.
Sample Code:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace testvar
{
Class Program
{
// Example of delayed execution of the LINQ Query
Static void main (string [] ARGs)
{
Int [] intary = new int [] {1, 2, 3, 4, 5, 6 };
// Define query conditions for varset
VaR varset = from X in intary
Where X % 2 = 0
Select X;
// Output query results
Foreach (var v in varset)
{
Console. Write (V. tostring () + "");
}
Console. writeline ();
// Modify the array element
Intary [0] = 8;
// Output query results
Foreach (var v in varset)
{
Console. Write (V. tostring () + "");
}
Console. readkey ();
}
}
}
The output of this program is:
We can see that after modifying the array elements, we can use iterations to get the latest results without having to redefine the LINQ query for varset.
So how can we make the LINQ query be executed immediately? Enumerable defines many extension methods, such as toarray <t> (), todictionary <tsource, tkey> (), and tolist <t>, they allow us to capture the results of the LINQ query with a strong type container. Then, the container will no longer "Connect" to the LINQ expression, and you can operate it independently. Sample Code:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace testvar
{
Class Program
{
Static void main (string [] ARGs)
{
Int [] intary = new int [] {1, 2, 3, 4, 5, 6 };
// Use a strong type to obtain query results immediately
List <int> intlist = (from X in intary
Where X % 2 = 0
Select X). tolist ();
// Output query results
Foreach (int v in intlist)
{
Console. Write (V. tostring () + "");
}
Console. readkey ();
}
}
}