Deferred Execution executes a query only when a loop starts. What I mean here is that, we iterate through the query variable to get the result. Here the result variable does not contain the actual result. To get the result, we may iterate through the result (query) variable in a loop as many times as we want. We do deferred execution mainly when multiple values are being returned from the query. Example using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace ConsoleApplication3{ class Program { static void Main(string[] args) { DataClasses1DataContext context = new DataClasses1DataContext(); var result = from r in context.Persons select r; foreach (var a in result) { Console.WriteLine(a.FirstName + "" + a.LastName); } Console.ReadKey(true); } }}Output Immediate Execution happens when LINQ query returns a single value. Above query is returning a single value so it can be executed immediately.Example using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication3{ class Program { static void Main(string[] args) { DataClasses1DataContext context = new DataClasses1DataContext(); var numberOfRecords = (from r in context.Persons select r).Count(); Console.WriteLine(numberOfRecords); Console.ReadKey(true); } }}Output If we want to make a query returning multiple values or sequence of values as immediate then we need to explicitly convert the result in ToList(). So above query is returning multiple values and would be executed immediately.Example using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication3{ class Program { static void Main(string[] args) { DataClasses1DataContext context = new DataClasses1DataContext(); var result1 = (from r in context.Persons select r).ToList(); foreach (var a in result1) { Console.WriteLine(a.FirstName + "" + a.LastName); } Console.ReadKey(true); } }}Output
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: