Lalitya
Lalitya

Reputation: 729

Execution flow of a linq query

case1

var numbers = new List<int>();
numbers.Add (1);
IEnumerable<int> query = numbers.Select (n => n * 10);    // Build query
numbers.Add (2);

//Use or execute query  

case2

var numbers = new List<int>() { 1, 2 };
numbers.Add(4);
List<int> query  = numbers
  .Select (n => n * 10) 
  .ToList();                      // Executes immediately into a List<int>
numbers.Add(3);
numbers.Clear();

//Use or execute query

Why in the first case query contains both 1,2

In second case query contains only 1,2,4 but not 3,is it because we are calling .ToList() method.

Upvotes: 0

Views: 636

Answers (5)

user1042479
user1042479

Reputation: 41

the linq will call the DB and return actul data only when .tolist() will call.

Upvotes: 0

fardjad
fardjad

Reputation: 20424

In case1 query executed after you enumerated it.

In case2 the result doesn't contain 3 because you've already executed the query and holding it's result (which is an IEnumarable object) in query variable (and it's not a Linq Query object.)

Upvotes: 0

ratneshsinghparihar
ratneshsinghparihar

Reputation: 301

linq uses the concept of late execution means it will execute the query only when it call for the actual work like .first .list etc.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191058

Any Linq method that returns IEnumerable<T> is deferred, meaning it won't return items until enumerated.

ToList<T>() is a non-deferred operation.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039548

It's because the query is not executed until you start enumerating over the resultset (by either calling .ToArray(), .ToList(), or simply write a foreach)

IEnumerable<int> query = numbers.Select (n => n * 10);

doesn't execute anything. It's the the lazy nature of LINQ.

Upvotes: 5

Related Questions