LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.
There are two type of linq query execution are given below:
Deferred query execution
In deferred execution query is executed when the query variable is iterated by using loop.
Deferred execution enables multiple queries to be combined or queries to be extended. when a query is extended, it is modified to include the new operations, and the eventual execution will reflect the changes.
DataContext objcontext = new DataContext(); var query = from customer in objcontext.Customers
where customer.City == "Pune" select customer; // Query does not execute foreach (var Customer in query) // Query executes { Console.WriteLine(Customer.Name); }
Deferred execution provides the facility of query reusability since it always fetches the uploaded data from the data source which exists at the time of each execution.
Immediate Query Execution
In immediate execution query is executed at the point of its declaration. It is the query that return a singleton value are executed immediately. Some example of singleton queries are
Average, Count, First and Max . These execute immediately because the query must produce a sequence to calculate the singleton result.
DataContext objcontext = new DataContext();
var query = (from customer in objcontext .Customers
where customer.City == "Pune" select customer).Count(); // Query execute
Immediate execution does not provide the facility of query re-usability. you could also force execution by putting the foreach or For Each loop immediately after the query expression, but by calling ToList or ToArray you cache all the data in single collection object.
No comments:
Post a Comment