Delayed execution of LINQ queries

Source: Internet
Author: User

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 ();
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.