When you call Count , it does not materialize the entire data set. Rather, he prepares and executes a request such as
SELECT COUNT(*) FROM ...
Using ExecuteScalar to get the result.
When you call Where and Select , it does not materialize (it is assumed that q is IQueryable ). Instead, it simply prepares a request like
SELECT col1, col2, ... FROM ...
But actually it is not fulfilled. It will execute the request only when calling GetEnumerator on q . You will rarely do this directly, but something like the following will execute your request:
var arry = q.ToArray(); var list = q.ToList(); foreach(var rec in q) ...
It will execute this query only once, so having multiple foreach loops will not create multiple database queries. Of course, if you create a new IQueryable -based IQueryable (e.g. var q2 = q.Where(...) ), it will not be tied to the result set used by q , so it will have to query the database again.
I have checked your code in LINQPad and it seems that all your analyzes are correct.
source share