问题
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.
回答1:
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.
回答2:
Any Linq method that returns IEnumerable<T>
is deferred, meaning it won't return items until enumerated.
ToList<T>()
is a non-deferred operation.
回答3:
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.
回答4:
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.)
回答5:
the linq will call the DB and return actul data only when .tolist() will call.
来源:https://stackoverflow.com/questions/7993167/execution-flow-of-a-linq-query