Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the following LINQ statement work?

Tags:

c#

.net

linq

People also ask

What is a LINQ statement?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.

How does LINQ to SQL work?

In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution.

What is LINQ when and how would you use it?

LINQ is a data querying API that provides querying capabilities to . NET languages with a syntax similar to a SQL. LINQ queries use C# collections to return data. LINQ in C# is used to work with data access from sources such as objects, data sets, SQL Server, and XML.

What is LINQ used for in C#?

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.


The output is 2,4,6,8 because of deferred execution.

The query is actually executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution.

-- Suprotim Agarwal, "Deferred vs Immediate Query Execution in LINQ"

There is another execution called Immediate Query Execution, which is useful for caching query results. From Suprotim Agarwal again:

To force immediate execution of a query that does not produce a singleton value, you can call the ToList(), ToDictionary(), ToArray(), Count(), Average() or Max() method on a query or query variable. These are called conversion operators which allow you to make a copy/snapshot of the result and access is as many times you want, without the need to re-execute the query.

If you want the output to be 2,4,6, use .ToList():

var list = new List<int>{1,2,4,5,6};
var even = list.Where(m => m%2 == 0).ToList();
list.Add(8);
foreach (var i in even)
 {
    Console.WriteLine(i);
 }

This has happened because of deferred execution, which means that the calculation of the expression is not executed until it is needed someplace. This makes the performance better if the data is too large.