C#

Deferred Query Execution and Immediate Query Execution in LINQ

Programmingempire

In this post, I will explain Deferred Query Execution and Immediate Query Execution in LINQ.

Basically, a query formulated in LINQ may exhibit one of the two kinds of behaviors during execution. These two kinds of behaviors are called deferred query execution and immediate query execution.

In the case of deferred query execution, the query is formulated first. Later, it can be executed. In contrast, for immediate query execution, the query is forced to execute immediately.

Examples of Deferred Query Execution

The following examples show how the query is created in the first place and later executed through the foreach loop. Hence, the execution of the query is said to be deferred.

As shown below, the query uses an array of integers as the data source and retrieves the square root of all positive values. Later, the foreach loop iterates over the query variable q and executes the query.

int[] arr = { 3, 11, -90, 66, 678, -45, 2, -7, 12 };
var q = from x in arr
        where x > 0
        select Math.Round(Math.Sqrt(x),2);
foreach (double d in q)
        Console.Write(d + "  ");
Console.WriteLine();

Output

Deferred Query Execution
Deferred Query Execution

Examples of Immediate Query Execution

The following examples show the query execution at the time of creation and returning the result immediately. Therefore, the execution of the query is immediate.

As can be seen, the first query in the following example is the same as the earlier one except it makes use of the element operator ToArray(). Hence, the execution of the query takes place in the same statement, and the double type array gets the resulting values.

After that, the next query makes use of the Count() function and returns the count of positive elements in the array.

Further, the next two queries return the maximum and the average of the square roots respectively.

double[] arr1= (from x in arr
                           where x > 0
                           select Math.Round(Math.Sqrt(x), 2)).ToArray();
            foreach (double d in arr1)
                Console.Write(d + "  ");
            Console.WriteLine();

            int count = (from x in arr
                         where x > 0
                         select x).Count();
            Console.WriteLine($"Count of +ve Numbers: {count}");
            double max = (from x in arr
                       where x > 0
                       select Math.Round(Math.Sqrt(x), 2)).Max();
            Console.WriteLine($"Maximum: {max}");
            double avg = (from x in arr
                          where x > 0
                          select Math.Round(Math.Sqrt(x), 2)).Average();
            Console.WriteLine($"Average of square roots: {Math.Round(avg,2)}");

Output

Immediate Query Execution
Immediate Query Execution

Comparing Deferred Query Execution and Immediate Query Execution in LINQ

In general, the deferred query execution makes use of the select clause and is the default in LINQ. The query is not executed at the same statement which creates it. Rather, its execution is deferred till the query-variable is iterated using a foreach loop. One of the benefit of deferred query execution is that it makes the query reusable and the query always brings the latest data.

In contrast, when we use an aggregate function or element operator it results in the immediate execution of the query. In the case of an aggregate operator, the query immediately returns a value like count or average. Whereas, an element operator like ToArray() returns the array as the result of the query.

Summary

To summarize, in this article, you have learned about Deferred Query Execution and Immediate Query Execution in LINQ. Also, a comparison of the two approaches is also discussed. While the default approach of query execution is the deferred query execution that has better performance than the immediate execution. In case, you want the result of the query in the same place where you formulate it, you can use the appropriate function.


Further Reading

Selection Sort in C#

Insertion Sort in C#

Bubble Sort in C#

How to Create Instance Variables and Class Variables in Python

Comparing Rows of Two Tables with ADO.NET

Example of Label and Textbox Control in ASP.NET

One Dimensional and Two Dimensuonal Indexers in C#

Private and Static Constructors in C#

Methods of Array Class

Anonymous Functions in C#

Programs to Find Armstrong Numbers in C#

Matrix Multiplication in C#

One Dimensional and Two Dimensional Indexers in C#

Static Class Example in C#

Rotating an Array in C#

Generic IList Interface and its Implementation in C#

Recursive Binary search in C#

C# Practice Questions

Creating Navigation Window Application Using WPF in C#

Find Intersection Using Arrays

An array of Objects and Object Initializer

Performing Set Operations in LINQ

Using Quantifiers in LINQ

Data Binding Using BulletedList Control

Grouping Queries in LINQ

Generic Binary Search in C#

Understanding the Quantifiers in LINQ

Join Operation using LINQ

Deferred Query Execution and Immediate Query Execution in LINQ

Examples of Query Operations using LINQ in C#

An array of Objects and Object Initializer

Language-Integrated Query (LINQ) in C#

How Data Binding Works in WPF

Examples of Connected and Disconnected Approach in ADO.NET

New Features in C# 9

IEnumerable and IEnumerator Interfaces

KeyValuePair and its Applications

C# Root Class – Object

Access Modifiers in C#

Learning Properties in C#

Learning All Class Members in C#

Examples of Extension Methods in C#

How to Setup a Connection with SQL Server Database in Visual Studio

Understanding the Concept of Nested Classes in C#

LINQ To SQL Examples

A Beginner’s Tutorial on WPF in C#

Explaining C# Records with Examples

Everything about Tuples in C# and When to Use?

Creating Jagged Arrays in C#

Linear Search and Binary search in C#

Learning Indexers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Basic Examples

IEqualityComparer Interface

programmingempire

You may also like...